Sunday, 6 November 2016

LINQ equivalent of foreach for IEnumerable



I'd like to do the equivalent of the following in LINQ, but I can't figure out how:




IEnumerable items = GetItems();
items.ForEach(i => i.DoStuff());



What is the real syntax?


Answer



There is no ForEach extension for IEnumerable; only for List. So you could do



items.ToList().ForEach(i => i.DoStuff());


Alternatively, write your own ForEach extension method:



public static void ForEach(this IEnumerable enumeration, Action action)

{
foreach(T item in enumeration)
{
action(item);
}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...