foreach 与 someList.ForEach(){} [英] foreach vs someList.ForEach(){}

查看:28
本文介绍了foreach 与 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>
}

其他方式:

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 使用 for 循环来迭代集合,所以这是有效的(.net 4.5 之前 - 实现改变并且它们都抛出):

Because .ForEach uses a for loop to iterate the collection, this is valid (edit: prior to .net 4.5 - the implementation changed and they both throw):

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;dr:不要将此代码复制粘贴到您的应用程序中!

这些示例不是最佳实践,它们只是为了演示 ForEach()foreach 之间的区别.

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

for 循环内的列表中删除项目可能会产生副作用.对此问题的评论中描述了最常见的一种.

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.

通常,如果您希望从列表中删除多个项目,您需要将确定删除哪些项目与实际删除分开.它不会让您的代码保持紧凑,但可以保证您不会遗漏任何项目.

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 与 someList.ForEach(){}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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