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:
List<String> strings = new List<String>() { "foo", "bar", "baz" };
strings.ForEach(st => { Console.WriteLine(st); });
By using Select you're basically defining anonymous functions with the following body.
Console.WriteLine(st);
return 1;
So, Console.WriteLine will only be triggered when you're iterating through the list, like this:
var x= strings.Select(st => { Console.WriteLine(st); return 1; });
foreach (var i in x){ }
or x.ToList()
And that is wrong, use ForEach :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With