I was hoping to use Select as a functional foreach. When I do the following, I expected it to print
foo
bar
baz
it doesn’t print anything however. Howcome? The code is
List<String> strings = new List<String>(){"foo", "bar", "baz"};
strings.Select(st => { Console.WriteLine(st); return 1; });
Use ForEach:
By using Select you’re basically defining anonymous functions with the following body.
So, Console.WriteLine will only be triggered when you’re iterating through the list, like this:
or
x.ToList()And that is wrong, use ForEach 🙂