LINQ 的副作用 [英] LINQ side effects
本文介绍了LINQ 的副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以用 LINQ (.Select)
) 中的 lambda 表达式替换 foreach
循环?
is it possible to substitute a foreach
loop with a lambda expression in LINQ (.Select)
)?
List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
Console.WriteLine(i);
致:
List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);
推荐答案
没有与 foreach 等效的 Linq,尽管自己实现一个相当容易.
There is no Linq equivalent of foreach, although it is fairly easy to implement one yourself.
Eric Lippert 给出了很好的描述这里 为什么这没有在 Linq 本身中实现.
Eric Lippert gives a good description here of why this was not implemented in Linq itself.
但是,如果您的集合是一个列表(在您的示例中似乎是这样),您可以使用 List.ForEach:
However, if your collection is a List (which it appears to be in your example), you can use List.ForEach:
myList.ForEach(item => Console.WriteLine(item));
这篇关于LINQ 的副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文