Are there std::for_each algorithm analog in C# (Linq to Objects)

396 Views Asked by At

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();
}
2

There are 2 best solutions below

4
On BEST ANSWER

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.

0
On

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.