Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select fails to print to console

Tags:

c#

select

linq

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; });
like image 656
Martijn Avatar asked Feb 20 '13 14:02

Martijn


1 Answers

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

like image 112
animaonline Avatar answered Nov 15 '22 09:11

animaonline