2

I'm trying to print even numbers from 1 to 10 using LINQ with the following code

Enumerable.Range(1, 10).Select(n => n%2 == 0).ToString().ToList().ForEach(Console.WriteLine);

Now instead of printing even numbers its printing True or False statements. Where am i doing mistake here?

Jaganmohanreddy
  • 391
  • 4
  • 19

2 Answers2

3

You should do this:

Enumerable.Range(1, 10).Where(n => n%2 == 0).ToList().ForEach(Console.WriteLine);

otherwise you're selecting the bool value, and not applying the filter :)

Noctis
  • 11,507
  • 3
  • 43
  • 82
  • No worries. seems like you got the same answer about the same time :). Have a look @ msdn 101 linq guide, and have a look at linqpad as well, they will get you on the right path in no time – Noctis Jun 28 '15 at 08:35
2

You are using Select instead of where

Enumerable.Range(1, 10).Where(n => n%2 == 0).ForEach(Console.WriteLine)

Select is creating new object for each evaluation, which evaluates to a boolean in this case.

n00b
  • 1,832
  • 14
  • 25
  • when i run your query i got the 'System.Collections.Generic.IEnumerable' does not contain a definition for 'ForEach' and no extension method 'ForEach' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?) error. the correct answer would be adding ToList() after the where clause in the above query. – Jaganmohanreddy Jun 28 '15 at 08:11
  • 1
    You are right, though I usually add the ForEach extension to IEnumerable like this : http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet – n00b Jun 28 '15 at 08:18
  • This would be more efficient than storing the results in a List and then iterating through them – n00b Jun 28 '15 at 08:19
  • @n00b I find it worth mentioning that the first comment on the question you linked to links to [this](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx) blog post from Eric Lippert where he argues why a `ForEach` extension on `IEnumerable` should _not_ be used. – Bill Tür stands with Ukraine Jun 28 '15 at 18:42
  • @ThomasSchremser, thanks for sharing that. Though this might be better than ToList().ForEach() pattern, still probably something to avoid – n00b Jun 28 '15 at 22:00