显然有许多方法可以迭代集合。很好奇是否有什么不同,或者为什么你用一种方式而不是另一种。

第一类型:

List<string> someList = <some way to init>
foreach(string s in someList) {
   <process the string>
}

其他方式:

List<string> someList = <some way to init>
someList.ForEach(delegate(string s) {
    <process the string>
});

我想,除了我上面使用的匿名委托,你还可以指定一个可重用的委托。


当前回答

为了好玩,我将List弹出到reflector中,结果是c#:

public void ForEach(Action<T> action)
{
    if (action == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
    }
    for (int i = 0; i < this._size; i++)
    {
        action(this._items[i]);
    }
}

类似地,foreach使用的枚举器中的MoveNext是这样的:

public bool MoveNext()
{
    if (this.version != this.list._version)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
    }
    if (this.index < this.list._size)
    {
        this.current = this.list._items[this.index];
        this.index++;
        return true;
    }
    this.index = this.list._size + 1;
    this.current = default(T);
    return false;
}

列表中。ForEach比MoveNext更精简——处理更少——将更有可能JIT成高效的东西。

此外,foreach()将分配一个新的Enumerator。GC是你的朋友,但如果你重复做同样的foreach,这将产生更多的一次性对象,而不是重用同一个委托- but -这确实是一个边缘情况。在典型用法中,您将看到很少或没有区别。

其他回答

List.ForEach()被认为更具功能性。

List.ForEach()表示你想做什么。Foreach(列表中的项目)也确切地说明了你想要如何完成它。这就剩下List了。ForEach可以自由更改未来如何部分的实现。例如,一个假设的。net未来版本可能总是运行List。在并行的情况下,假设此时每个人都有一些cpu核心通常处于空闲状态。

另一方面,foreach (list中的项)让您对循环有更多的控制。例如,您知道项目将以某种顺序进行迭代,如果项目满足某些条件,则很容易在中间中断。


关于这个问题的一些最新评论可在此查阅:

https://stackoverflow.com/a/529197/3043

为了好玩,我将List弹出到reflector中,结果是c#:

public void ForEach(Action<T> action)
{
    if (action == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
    }
    for (int i = 0; i < this._size; i++)
    {
        action(this._items[i]);
    }
}

类似地,foreach使用的枚举器中的MoveNext是这样的:

public bool MoveNext()
{
    if (this.version != this.list._version)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
    }
    if (this.index < this.list._size)
    {
        this.current = this.list._items[this.index];
        this.index++;
        return true;
    }
    this.index = this.list._size + 1;
    this.current = default(T);
    return false;
}

列表中。ForEach比MoveNext更精简——处理更少——将更有可能JIT成高效的东西。

此外,foreach()将分配一个新的Enumerator。GC是你的朋友,但如果你重复做同样的foreach,这将产生更多的一次性对象,而不是重用同一个委托- but -这确实是一个边缘情况。在典型用法中,您将看到很少或没有区别。

我知道有两件事让他们不一样。去我!

首先,有一个典型的错误,即为列表中的每个项目创建一个委托。如果你使用foreach关键字,你所有的委托最终都会指向列表的最后一项:

    // A list of actions to execute later
    List<Action> actions = new List<Action>();

    // Numbers 0 to 9
    List<int> numbers = Enumerable.Range(0, 10).ToList();

    // Store an action that prints each number (WRONG!)
    foreach (int number in numbers)
        actions.Add(() => Console.WriteLine(number));

    // Run the actions, we actually print 10 copies of "9"
    foreach (Action action in actions)
        action();

    // So try again
    actions.Clear();

    // Store an action that prints each number (RIGHT!)
    numbers.ForEach(number =>
        actions.Add(() => Console.WriteLine(number)));

    // Run the actions
    foreach (Action action in actions)
        action();

列表中。每个方法都没有这个问题。迭代的当前项按值作为参数传递给外部lambda,然后内部lambda在自己的闭包中正确地捕获该参数。问题解决了。

(遗憾的是,我认为ForEach是List的成员,而不是扩展方法,尽管很容易自己定义它,因此您可以在任何可枚举类型上使用此功能。)

其次,ForEach方法有一定的局限性。如果你通过使用yield return来实现IEnumerable,你不能在lambda中做yield return。因此,通过循环遍历集合中的项以获得返回值是不可能的。您必须使用foreach关键字,并通过手动在循环中复制当前循环值来解决闭包问题。

更多的在这里

我猜somlist . foreach()调用可以很容易地并行化,而正常的foreach不那么容易并行运行。 您可以很容易地在不同的核心上运行几个不同的委托,这对于普通的foreach来说并不容易做到。 这只是我的小意思

整个ForEach作用域(委托函数)被视为一行代码(调用该函数),您不能设置断点或进入代码。如果发生未处理的异常,则标记整个块。