Is there any method like ForEach for IList?

Joe.wang picture Joe.wang · Dec 19, 2012 · Viewed 52.5k times · Source

Possible Duplicate:
LINQ equivalent of foreach for IEnumerable<T>

List<T> has a method called ForEach which executes the passed action on each element of it.

var names = new List<String>{ "Bruce", "Alfred", "Tim", "Richard" };

names.ForEach(p =>  { Console.WriteLine(p); });

But what if names is not a List<T> but an IList<T>? IList<T> doesn't have a method like ForEach.

Is there some alternative?

Answer

O. R. Mapper picture O. R. Mapper · Dec 19, 2012

Use a foreach loop:

foreach (var p in names) {
    Console.WriteLine(p);
}

There is no reason to use delegates and extension methods all over the place if that doesn't actually improve readability; a foreach loop is not any less explicitly telling readers what's being done than a ForEach method.