Why is the ForEach method used only in the List <T> collection?

Possible duplicate:
Why is there no ForEach extension method in the IEnumerable interface?

First let me point out that I'm referring to a method List<T>, not a C # keyword. What would Microsoft assume that the Foreach method is in a collection List<T>, but does not have another type of collection / enumerable in particular IEnumerable<T>?

I just opened this method the other day and found that it is a very good syntax for replacing traditional foreach loops that execute only one or two series of methods for each object.

It seems like it would be rather trivial to create an extension method that performs the same function. I guess I'm looking at why MS made this decision and based on this, if I just have to make an extension method.

+3
source share
4 answers

Eric Lippert answered this question many times, including parallel loops , the functional syntax ForEachdoes not add a lot of expressive power, and it is slightly less efficient than a regular loop ForEachdue to delegate calls.

If you really want a ForEachfor IEnumerable<T>, its not hard to write:

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

    // Here a lazy, streaming version:
    public static IEnumerable<T> ForEachLazy<T>( this IEnumerable<T> seq, Action<T> action )
    {
        foreach( var item in seq )
        {
            action( item );
            yield return item;
        }
    }
}
+17
source

- .NET 2.0. - ( , , ).

, , # 3 , , , , LINQ, Select, , . , ForEach foreach, .

+3
source

To get an answer from Raymond Chen (who was circumcised from Eric Gunnerson):

Each function starts with -100 points.

In principle, someone would have to write it and thereby take the time away from some other function. Since you can create ForEach()yourself trivially, it will never take precedence over other, less trivial functions.

Plus ForEach()precedes extension methods.

+1
source

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


All Articles