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?
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.