LINQ的副作用 [英] LINQ side effects
本文介绍了LINQ的副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有可能替代一个的foreach
循环与LINQ(。选择)
)<?lambda表达式/ p>
列表< INT> L = {1,2,3,4,5};
的foreach(INT I在升)
Console.WriteLine(ⅰ);
要:
列表与LT; INT> L = {1,2,3,4,5};
l.Select(/ *打印到控制台* /);
解决方案
有没有LINQ的等价的foreach,虽然它是相当容易实现一个自己。
埃里克利珀提供了一个很好的描述的here 。
不过,如果你的收集一个List(这似乎是在你的例子),你可以使用 List.ForEach :
myList.ForEach(项目=> Console.WriteLine(项目));
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);
To:
List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);
解决方案
There is no Linq equivalent of foreach, although it is fairly easy to implement one yourself.
Eric Lippert gives a good description here of why this was not implemented in Linq itself.
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屋!
查看全文