开发者

ForEach -- where are you? [duplicate]

This question already has answers here: Closed 11 years ago.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜