C#:List<T>.ForEach(...) 比普通 foreach 循环有什么好处?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1924535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: Any benefit of List<T>.ForEach(...) over plain foreach loop?
提问by Cristian Diaconescu
I'm wondering why List<T>.ForEach(Action<T>)
exists.
我想知道为什么List<T>.ForEach(Action<T>)
存在。
Is there any benefit/difference in doing :
这样做是否有任何好处/差异:
elements.ForEach(delegate(Element element){ element.DoSomething(); });
over
超过
foreach(Element element in elements) { element.DoSomething();}
?
?
采纳答案by Justin Long
One key difference is with the .ForEach method you can modify the underlying collection. With the foreach syntax you'll get an exception if you do that. Here's an example of that (not exactly the best looking but it works):
一个主要区别是使用 .ForEach 方法可以修改基础集合。使用 foreach 语法,如果你这样做,你会得到一个例外。这是一个例子(不是最好看,但它有效):
static void Main(string[] args) {
try {
List<string> stuff = new List<string>();
int newStuff = 0;
for (int i = 0; i < 10; i++)
stuff.Add(".");
Console.WriteLine("Doing ForEach()");
stuff.ForEach(delegate(string s) {
Console.Write(s);
if (++newStuff < 10)
stuff.Add("+"); // This will work fine and you will continue to loop though it.
});
Console.WriteLine();
Console.WriteLine("Doing foreach() { }");
newStuff = 0;
foreach (string s in stuff) {
Console.Write(s);
if (++newStuff < 10)
stuff.Add("*"); // This will cause an exception.
}
Console.WriteLine();
}
catch {
Console.WriteLine();
Console.WriteLine("Error!");
}
Console.ReadLine();
}
回答by Yuriy Faktorovich
回答by Mehrdad Afshari
It's very likely to be faster(you shouldn't choose one over the other merely because of the small performance benefits, unless you're dealing with computationally heavy number crunching or graphics application and you need to get the most out of processor cycles) and you can pass delegates directly to it which may be convenient in some cases:
它很可能更快(您不应该仅仅因为性能优势很小而选择另一个,除非您正在处理计算量很大的数字运算或图形应用程序,并且您需要充分利用处理器周期)和您可以将委托直接传递给它,这在某些情况下可能很方便:
list.ForEach(Console.WriteLine); // dumps the list to console.