Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 316
Alexander Beletsky Avatar asked Mar 05 '26 16:03

Alexander Beletsky


2 Answers

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.

like image 51
Dan Abramov Avatar answered Mar 08 '26 05:03

Dan Abramov


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.

like image 40
Yodan Tauber Avatar answered Mar 08 '26 04:03

Yodan Tauber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!