Vikram
Vikram

Reputation: 6877

how do you execute a function on a List of objects using LINQ

I want to execute a function on all the objects within a List of objects using LINQ. I know i saw something similar on SO before but after several failed search attempts, i am posting this question

Upvotes: 3

Views: 7834

Answers (1)

JaredPar
JaredPar

Reputation: 755457

Try the following if it is actually of type List<T>.

C#

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 on any general IEnumerable<T> type. Although it's easy to code such a function

C#

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 any IEnumerable<T> which makes it usable from practically any LINQ query.

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

EDIT

Note to use the .ForEach for VB.Net. You must chose a function that returns a value. It's a limitation of lambda expressions in VB.Net 9 (VS 2009). But there is o work around. Say you want to call SomeMethod which is a Sub. Simply create a wrapper which returns an empty value

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

Upvotes: 14

Related Questions