How do you execute a function in a list of objects using LINQ

I want to execute a function for all objects in a list of objects using LINQ. I know I saw something similar on SO before, but after several unsuccessful search attempts, I am posting this question

+3
source share
1 answer

Try the following if it really has a type List<T>.

FROM#

var list = GetSomeList();
list.ForEach( x => SomeMethod(x) );
' Alternatively
list.ForEach(SomeMethod);

Vb.net

Dim list = GetSomeList();
list.ForEach( Function(x) SomeMethod(x) );

Unfortunately .ForEach is only defined on List<T>, so it cannot be used for any general type IEnumerable<T>. Although it’s easy to code such a function

FROM#

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

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

With this, you can run .ForEach on anyone IEnumerable<T>that makes it suitable for using almost any LINQ query.

var query = from it in whatever where it.SomeProperty > 42;
query.ForEach(x => Log(x));

EDIT

.ForEach VB.Net. , . - VB.Net 9 (VS 2009). . , 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
+14

Source: https://habr.com/ru/post/1707968/


All Articles