2

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>.ForEach(Action<T> action);
Community
  • 1
  • 1
Glenn Ferrie
  • 9,617
  • 3
  • 37
  • 67
  • 6
    See this link for a pretty definitive explanation: http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx – dlev Jul 13 '11 at 02:38
  • There are no elements available to loop over with foreach until you actually execute the query by using ToList() – JK. Jul 13 '11 at 02:39
  • @JK - If I can 'Count()' and get 'First()' why cant I act on each element? – Glenn Ferrie Jul 13 '11 at 02:41
  • @dlex -- i will review, why is that not a subitted answer? – Glenn Ferrie Jul 13 '11 at 02:41
  • @Glenn It's not my answer, it's someone else's. I try to just post links as comments unless they're directly to documentation. – dlev Jul 13 '11 at 02:45
  • Because Count and First are for querying, whereas ForEach is for acting. Eric Lippert has the exact reasoning here: http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx – Michael Stum Jul 13 '11 at 02:51

2 Answers2

3

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);
      }
   }
}
agent-j
  • 25,367
  • 5
  • 47
  • 76
1

There's been much discussion over this topic:

See:

Community
  • 1
  • 1
Justin Shield
  • 2,360
  • 14
  • 12