ForEach -- where are you? [duplicate]
Possible Duplicate:
Why is there not a ForEach extension method on the IEnumerable interface?
I love the .ForEach method on List<T> in C#. How is this not one of the suite of Extension Methods on IEnumerable<T>?
Why do I have to call .ToList() my collection in order to call an action on each element? Please tell me why? Thank you.
List<T>.F开发者_开发问答orEach(Action<T> action);
Language INtegrated Query (LINQ). Not Language Integrated Extensions (LIEs).
You are particularly speaking of LINQ-to-objects. The other LINQs (to-SQL, to-XML), etc. would have more trouble implementing arbitrary logic.
Nothing stops you from implementing it yourself, though.
public static class Extensions
{
public static void ForEach<T> (this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action (item);
}
}
}
There's been much discussion over this topic:
See:
- LINQ equivalent of foreach for IEnumerable<T>
- Lambda Expression using Foreach Clause
精彩评论