score:14

Accepted answer

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

Related Query