LINQ side effects
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开发者_如何学Go, 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));
For any IEnumerable
, you can do:
items.Any(item =>
{
Console.WriteLine(item);
return false;
}
But this would be utterly wrong! It's like using a shoe to hammer the nail. Semantically, it does not make sense.
Use List.ForEach instead.
You can use the List<T>.ForEach
method.
l.ForEach(i => Console.WriteLine(i));
List.ForEach uses action delegate. Henceforth that will the right choice.
精彩评论