在 LINQ (.Select
) 中,是否可以用 lambda 表达式代替 foreach
循环?
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 */);
虽然没有Linq的foreach等效语法,但自己实现一个相对容易。
Eric Lippert在这里很好地描述了为什么Linq本身没有实现此功能。
然而,如果您的集合是List(在您的示例中似乎是这样),则可以使用List.ForEach:
myList.ForEach(item => Console.WriteLine(item));
对于任何 IEnumerable
,您可以执行以下操作:
items.Any(item =>
{
Console.WriteLine(item);
return false;
}
List.ForEach使用Action委托。从现在开始,这将是正确的选择。
.ToList()
,然后是.ForEach(Console.WriteLine)
。 - Harry Pehkonen