为什么ForEach方法只在列表

为什么ForEach方法只在列表

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

问题描述

$ b首先,让我指定我引用 List< T> 方法,而不是C#关键字。 Microsoft的推理是在 List< T> 集合上有Foreach方法,但没有其他集合/枚举类型,特别是 IEnumerable< T& / code>?

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.

推荐答案

已多次回应此问题,其中包括,函数 ForEach 语法不会增加表达力的方式,因为委托调用而比常规的 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 for IEnumerable< T> ,不难写:

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;采集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:35