Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ side effects

Tags:

c#

foreach

linq

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 */);
like image 262
pistacchio Avatar asked Apr 12 '11 08:04

pistacchio


2 Answers

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));
like image 136
Rob Levine Avatar answered Oct 09 '22 05:10

Rob Levine


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.

like image 43
Muhammad Hasan Khan Avatar answered Oct 09 '22 06:10

Muhammad Hasan Khan