是否可以用 LINQ 中的 lambda 表达式替换 foreach
循环 (.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,尽管您自己实现一个相当容易。
Eric Lippert 给出了很好的描述 here为什么这没有在 Linq 本身中实现。
但是,如果您的集合是一个列表(在您的示例中似乎是),您可以使用 List.ForEach :
myList.ForEach(item => Console.WriteLine(item));
关于c# - LINQ 副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5632222/