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

Is there an analogue of std :: for_each algoritm in C # (Linq to Objects) to pass into it Func<>? how

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

instead

foreach(var elem in sequence)
{
  elem.Some();
}
+3
source share
2 answers

C # has an operator foreach.

As Jon hints (and Eric clearly indicates ), LINQ designers wanted to keep the methods without side effects, while foreachviolating this contract.

In fact, there is a foreachmethod that applies this predicate in classes List<T>and Array, but it was introduced in the .NET Framework 2.0, and LINQ only with 3.5. They are not connected.

, :

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

, , , .

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

, ol foreach .

, void Func<T>, Action<T>.
Func<T> , T Action<T> void, T.

+6

System.Collections.Generic.List<T> void ForEach(Action<T> action), . Array .

+3

Source: https://habr.com/ru/post/1790271/


All Articles