3

Are there std::for_each algoritm analog in C# (Linq to Objects), to be able to pass Func<> into it? Like

sequence.Each(p => p.Some());

instead of

foreach(var elem in sequence)
{
  elem.Some();
}
demongolem
  • 9,474
  • 36
  • 90
  • 105
Alexander Beletsky
  • 19,453
  • 9
  • 63
  • 86

2 Answers2

6

There is a foreach statement in C# language itself.

As Jon hints (and Eric explicitly states), LINQ designers wanted to keep methods side-effect-free, whereas ForEach would break this contract.

There actually is a ForEach method that does applies given predicate in List<T> and Array classes but it was introduced in .NET Framework 2.0 and LINQ only came with 3.5. They are not related.

After all, you can always come up with your own extension method:

public static void ForEach<T> (this IEnumerable<T> enumeration, Action<T> action)
{
    foreach (T item in enumeration)
        action (item);
}

I agree this is useful in case you already have a single parameter method and you want to run it for each element.

var list = new List<int> {1, 2, 3, 4, 5};
list.Where (n => n > 3)
    .ForEach (Console.WriteLine);

However in other cases I believe good ol' foreach is much cleaner and concise.

By the way, a single-paramether void method is not a Func<T> but an Action<T>.
Func<T> denotes a function that returns T and Action<T> denotes a void method that accepts T.

Community
  • 1
  • 1
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
  • It's not so much that it is possible that they wanted it side-effect-free, [it is a fact](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx). ;) – Jeff Mercado Feb 06 '11 at 08:19
  • Oh thank you! I thought I came across this somewhere on Eric's blog but wasn't sure. After all, he must've written about pretty much every aspect of the language by now. – Dan Abramov Feb 06 '11 at 08:29
  • does it mean, for generic case on Linq to Objects, there are no ForEach and foreach statement should be used, instead.. right ? – Alexander Beletsky Feb 06 '11 at 08:30
  • I think I just answered this question. In short, a) there is only `ForEach` on `List` and `Array` but it was introduced way before LINQ; b) designers of LINQ wanted it to be side-effect-free whereas `ForEach` extension method would break this convention; c) you can always write your own extension method that does the thing if you have reasons to do so. – Dan Abramov Feb 06 '11 at 08:33
3

System.Collections.Generic.List<T> has a method void ForEach(Action<T> action) which executes the supplied delegate per each list item. The Array class also exposes such a method.

Yodan Tauber
  • 3,907
  • 2
  • 27
  • 48