如何使用LINQ在对象列表上执行函数

Vik*_*ram 3 linq foreach

我想使用LINQ在对象List中的所有对象上执行一个函数.我知道我之前看过类似的东西,但在几次失败的搜索尝试之后,我发布了这个问题

Jar*_*Par 14

如果它实际上是类型,请尝试以下操作List<T>.

C#

var list = GetSomeList();
list.ForEach( x => SomeMethod(x) );
' Alternatively
list.ForEach(SomeMethod);
Run Code Online (Sandbox Code Playgroud)

VB.Net

Dim list = GetSomeList();
list.ForEach( Function(x) SomeMethod(x) );
Run Code Online (Sandbox Code Playgroud)

不幸的是.ForEach仅定义于此,List<T>因此不能用于任何常规IEnumerable<T>类型.虽然编写这样的功能很容易

C#

public static void ForEach<T>(this IEnumerable<T> source, Action<T> del) {
  foreach ( var cur in source ) {
    del(cur);
  }
}
Run Code Online (Sandbox Code Playgroud)

VB.Net

<Extension()> _
Public Sub ForEach(Of T)(source As IEnumerable(Of T), ByVal del As Action(Of T)
  For Each cur in source
    del(cur)
  Next
End Sub
Run Code Online (Sandbox Code Playgroud)

有了这个,您可以运行.ForEach IEnumerable<T>,使其几乎可以从任何LINQ查询中使用.

var query = from it in whatever where it.SomeProperty > 42;
query.ForEach(x => Log(x));
Run Code Online (Sandbox Code Playgroud)

编辑

注意使用.ForEach for VB.Net.您必须选择一个返回值的函数.这是VB.Net 9(VS 2009)中lambda表达式的限制.但是还有一些工作要做.假设你想调用SomeMethod这是一个Sub.只需创建一个返回空值的包装器

Sub SomeMethod(x As String) 
  ... 
End Sub

Function SomeMethodWrapper(x As String)
  SomeMethod(x)
  Return Nothing
End Function

list.ForEach(Function(x) SomeMethod(x)) ' Won't compile
list.ForEach(function(x) SomeMethodWrapper(x)) ' Works
Run Code Online (Sandbox Code Playgroud)