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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With