Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq/lambda question about .Select (newby learning 3.0)

I am playing with the new stuff of C#3.0 and I have this code (mostly taken from MSDN) but I can only get true,false,true... and not the real value :

        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

        var oddNumbers = numbers.Select(n => n % 2 == 1);

        Console.WriteLine("Numbers < 5:");
        foreach (var x in oddNumbers)
        {
            Console.WriteLine(x);
        }

How can I fix that to show the list of integer?

like image 587
Patrick Desjardins Avatar asked Oct 28 '08 01:10

Patrick Desjardins


2 Answers

Change your "Select" to a "Where"

    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    var oddNumbers = numbers.Where(n => n % 2 == 1);

    Console.WriteLine("Odd Number:");
    foreach (var x in oddNumbers)
    {
        Console.WriteLine(x);
    }

The "Select" method is creating a new list of the lambda result for each element (true/false). The "Where" method is filtering based on the lambda.

In C#, you could also use this syntax, which you may find clearer:

        var oddNumbers = from n in numbers
                         where n % 2 == 1
                         select n;

which the compiler translates to:

var oddNumbers = numbers.Where(n => n % 2 == 1).Select(n => n);
like image 145
TheSoftwareJedi Avatar answered Oct 20 '22 02:10

TheSoftwareJedi


numbers.Select(n => n % 2 == 1);

Change this to

numbers.Where(n => n % 2 == 1);

What select does is "convert" one thing to another. So in this case, it's "Converting" n to "n % 2 == 1" (which is a boolean) - hence you get all the true and falses.

It's usually used for getting properties on things. For example if you had a list of Person objects, and you wanted to get their names, you'd do

var listOfNames = listOfPeople.Select( p => p.Name );

You can think of this like so:

  • Convert the list of people into a list of strings, using the following method: ( p => p.Name)

To "select" (in the "filtering" sense of the word) a subset of a collection, you need to use Where.

Thanks Microsoft for the terrible naming

like image 30
Orion Edwards Avatar answered Oct 20 '22 02:10

Orion Edwards