LINQ equivalent of foreach for IEnumerable<T>

tags2k picture tags2k · Oct 14, 2008 · Viewed 520.6k times · Source

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

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

What is the real syntax?

Answer

Fredrik Kalseth picture Fredrik Kalseth · Oct 14, 2008

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

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

Alternatively, write your own ForEach extension method:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}