You can use the let
syntax in your code:
string test = "12,23,34,23,12";
var res = from string s in test.Split(',')
let u = s+s
select int.Parse(u);
Alternately, you could use the LINQ extension methods directly instead of the special syntax:
string test = "12,23,34,23,12";
var res = test.Split(',')
.Select(s => { var u = s + s; return int.Parse(u); });
Since the question was updated:
I don't mean to be disrespectful, but I think this solution isn't necessary.
Here's a bit of an exploration:
If we want to accept truly "arbitrary" lambdas like you say, then they can come from an outside source, and Wrap
does nothing because it's the same as f()
:
// with 'f' as some arbitrary lambda, then this:
var res = from string s in test.Split(',')
select f.Wrap();
// is the same as:
var res = from string s in test.Split(',')
select f();
But if you do this, f
can't depend upon s
in any way (for example, this way you can't write your example code):
// e.g. where does s come from?
var f = () => { var u = s+s; return int.Parse(u); };
// we can write it like this, as a function of 's':
var f2 = s => { var u = s+s; return int.Parse(u); };
//but then you can just use "select f2(s)" and we're back not needing Wrap any more
What we're really looking for is arbitrary closures over s
. For this to happen, the lambdas have to be defined inline, where s
is in scope, so you aren't really accepting truly "arbitrary" lambdas any more, and they have to be written directly in the code.
This is why I proposed the let
syntax, since any lambda you can come up with can be converted to that syntax, and it goes with the rest of the query syntax. This is what let
is designed for! :)
Alternately, you could just use lambdas which take parameters like f2
above.
If you really want to stick with the lambda syntax, I'd suggest using the extension methods. Like I said in my comment, it looks like you're looking for something halfway between query & extension syntax.
I'd be interested in why you want to use the lambda syntax with the query syntax?
Hope this helps :)