Why Doesn't IEnumerable<T> Have a ForEach Method?
In C#, types like List<T>
(and others such as ImmutableList<T>
) include a convenient ForEach
method. It can be seen as a more functional-style alternative to the traditional foreach
loop. For example:
var list = new List<int> { 1, 2, 3, 4, 5 };
// Traditional foreach loop
foreach (var n in list)
{
Console.WriteLine(n);
}
// The ForEach method achieves the same result
list.ForEach(n => Console.WriteLine(n));
Additionally, the Array
class provides a static ForEach
method that serves a similar purpose. However, you'll quickly notice that this handy method is not...