Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 */);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
422 views
Welcome To Ask or Share your Answers For Others

1 Answer

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...