tags:

views:

113

answers:

3
string grid = @"08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
string[] res = grid.Split(' ');

var lowNums = from n in res
              where n.Length > 0
              select int.Parse(n);

I am having trouble converting the above linQ statement to a lambda WHERE equivalent. The following works, but only returns am enumernable<string> whereas I want an enumerable<int>:

IEnumerable<string> all = res.Where(x => x.Length > 0);
+9  A: 

The following should work. You just forgot the select clause.

res.Where(n => n.Length > 0).Select(n => int.Parse(n));

The where clause will not change your data into an int. But, the Select(lambda) can.

jjnguy
+5  A: 

You need to include the call to int.Parse to convert the results to an int. Since you're doing this after the "where" clause, this will require a Select(), which basically allows you to change the form of your enumerable (ie: map it to a new type, in this case, convert from string to int):

var lowNums = res.Where(n => n.Length > 0).Select(n => int.Parse(n));
Reed Copsey
I wish answers were still sorted by age `:P`
jjnguy
that's great - works like a charm - thanks mate!
JoshBriggs
@Justin: Our answers were only about 10 seconds apart - though I only left mine because I had extra "text" describing ~why~ this was required, that your answer (at the time) was lacking. I'm still leaving this, though, as my description differs from yours (which is also correct ;) - and got a vote from me )
Reed Copsey
@Reed Yeah, I was comment on the fact that our initial answers were ~10 seconds apart and contained the same content. Great minds think alike.
jjnguy
+10  A: 

I am having trouble converting the above LINQ statement to a lambda Where() equivalent.

What you want to do then is carefully read section 7.16.2 of the C# specification. It will walk you step-by-step through the process.

It says:

A query expression with a where clause

from x in e
where f
...

is translated into

from x in ( e ) . Where ( x => f )
...

So your query

from n in res  
where n.Length > 0  
select int.Parse(n);  

is translated into

from n in (res).Where(n=>n.Length > 0)
select int.Parse(n)

That's the first stage of the translation. Now go back to the spec again:

A query expression of the form

from x in e select v

is translated into

( e ) . Select ( x => v )

So your translated-once-already query

from n in (res).Where(n=>n.Length > 0)
select int.Parse(n)

is further translated into

((res).Where(n=>n.Length > 0)).Select(n=>int.Parse(n))

and now it is not a query expression any more, so no more syntactic translation is done.

Eric Lippert