的foreach VS someList.Foreach(){} [英] foreach vs someList.Foreach(){}

查看:228
本文介绍了的foreach VS someList.Foreach(){}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有明显许多方法来遍历集合。好奇,如果有任何差异,或为什么你会使用一种方法比其他。

There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other.

第一类:

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

另一种方式:

Other Way:

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

我想从我的头顶,而不是匿名委托我用上面这一点,你必须你可以指定一个可重用的委托......

I suppose off the top of my head, that instead of the anonymous delegate I use above, you'd have a reusable delegate you could specify...

推荐答案

有一个重要的,并且是有用的,这两者之间的区别。

There is one important, and useful, distinction between the two.

由于.ForEach使用循环来遍历集合,这是有效的:

Because .ForEach uses a for loop to iterate the collection, this is valid:

someList.ForEach(x => if(x.RemoveMe) someList.Remove(x));

,而的foreach 使用一个枚举,所以这是无效的:

whereas foreach uses an enumerator, so this is not valid:

foreach(var item in someList)
  if(item.RemoveMe) someList.Remove(item);


TL;博士:不要copypaste这code到应用程序中

这些例子不是最好的做法,他们只是为了演示的的ForEach的差异()的foreach

These examples aren't best practice, they are just to demonstrate the differences between ForEach() and foreach.

从列表中删除项目中的循环可以有副作用。在评论中最常见的一种描述了这个问题。

Removing items from a list within a for loop can have side effects. The most common one is described in the comments to this question.

通常情况下,如果你正在寻找从列表中删除多个项目,你想分离出的项目,从实际删除删除的决心。它不会让你的code紧凑,但它保证你不会错过任何项目。

Generally, if you are looking to remove multiple items from a list, you would want to separate the determination of which items to remove from the actual removal. It doesn't keep your code compact, but it guarantees that you do not miss any items.

这篇关于的foreach VS someList.Foreach(){}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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