is it possible to substitute a foreach
loop with a lambda expression in LINQ (.Select)
)?
List l = {1, 2, 3, 4, 5};
forea
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.
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));
Use List.ForEach instead.
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.