LINQ side effects

后端 未结 5 1480
别那么骄傲
别那么骄傲 2020-12-11 02:43

is it possible to substitute a foreach loop with a lambda expression in LINQ (.Select))?

List l = {1, 2, 3, 4, 5};
forea         


        
相关标签:
5条回答
  • 2020-12-11 03:15

    You can use the List<T>.ForEach method.

    l.ForEach(i => Console.WriteLine(i));
    
    0 讨论(0)
  • 2020-12-11 03:22

    List.ForEach uses action delegate. Henceforth that will the right choice.

    0 讨论(0)
  • 2020-12-11 03:23

    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));
    
    0 讨论(0)
  • 2020-12-11 03:25

    Use List.ForEach instead.

    0 讨论(0)
  • 2020-12-11 03:32

    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.

    0 讨论(0)
提交回复
热议问题