Different Forms Of LinQ
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 a开发者_Python百科bove 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);
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.
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.
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));
加载中,请稍侯......
精彩评论