为什么的ForEach方法只对名单< T>采集? [英] Why is ForEach Method only on the List<T> collection?

查看:162
本文介绍了为什么的ForEach方法只对名单< T>采集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/101265/why-is-there-not-a-foreach-extension-method-on-the-ienumerable-interface">Why是不是有IEnumerable接口上一个foreach扩展方法?

首先,我要说明,我指的是在名单,其中,T&GT; 方法,而不是C#的关键字。这将是微软的推理具有的Foreach方法上的名单,其中,T&GT; 收集,但没有其他集合/枚举类型,特别是的IEnumerable&LT; T&GT;

First, let me specify I am refering to the List<T> method and not the C# keyword. What would be Microsoft's reasoning for having the Foreach method on the List<T> collection but no other collection/enumerable type, specifically IEnumerable<T>?

我刚刚发现这个方法有一天,发现它是非常好的语法,以取代传统的foreach循环,只有每个对象上执行的方法之一或2行。

I just discovered this method the other day, and found it to be very nice syntax for replacing traditional foreach loops that only perform one or 2 lines of methods on each object.

看起来这将是相当微不足道创建一个扩展方法,执行此相同的功能。我想我在看为什么MS作出这一决定,并依据,如果我只是做一个扩展方法。

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

推荐答案

埃里克利珀回应了这个问题无数次,包括在自己的博客

Eric Lippert has responded to this question numerous times, including on his blog.

他的回答一直是的ForEach()是明确用于其副作用的东西 - 而LINQ主要是打算成为一个无副作用的API定义预测和顺序操作。

His response has been that ForEach() is something you use explicitly for its side effects - whereas LINQ is largely intended to be a side-effect free API to define projections and manipulations on sequences.

用途如并行循环的,功能的ForEach 语法,不会增加太多的EX pressive权力的方式,它比常规略少高效的foreach 循环因委托调用。

Outside of uses like parallel loops, the functional ForEach syntax doesn't add much in the way of expressive power, and it is slightly less efficient than a regular foreach loop due to the delegate invocations.

如果你真的,真的想要一个的ForEach 的IEnumerable&LT; T&GT; ,它并不难写一个:

If you really, really want a ForEach for IEnumerable<T>, it's not hard to write one:

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

    // Here's 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;
        }
    }
}

这篇关于为什么的ForEach方法只对名单&LT; T&GT;采集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆