tags:

views:

3316

answers:

3

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?

+11  A: 

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);
TheSoftwareJedi
Thx it works, what is Select for if it doesn't select data?
Daok
It does select data. It's selecting the result of your lambda - which is a boolean value.
TheSoftwareJedi
thx!! Now I get it.
Daok
Just to let you know that var oddNumbers = numbers.Where(n => n % 2 == 1).Select(n); doesn't work.
Daok
I see what you mean, you were referring to my attempted compiler translation example. I fixed that - but I didn't mean for you to use that. Just the first answer that I gave (which compiled).var oddNumbers = numbers.Where(n => n % 2 == 1);
TheSoftwareJedi
+2  A: 
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

Orion Edwards
Terrible naming? "Select" is selecting, "Where" is filtering. Same as SQL...
TheSoftwareJedi
Yeah, same as SQL, but different to every other programming language (ruby, lisp, python, etc, etc) which use map for 'select' and select for 'where'
Orion Edwards
Thx for the information about the Select.
Daok
... and in F#, "map" is "Select", and "filter" is "Where". Very nice IMHO.
Martin R-L
A: 

"Select/Where " are quiet normal, nothing Odd i feel.

mahendren