Does the following generic function exist anywhere in the .NET 4.0 framework? I would like to reuse it if it does rather than writing it myself:
public static class Lambda
{
public static U Wrap<U>(Func<U> f)
{
return f();
}
}
It allows for the following construct (i.e., lambda expressions embedded in the select clause of a LINQ query):
string test="12,23,34,23,12";
var res=from string s in test.Split(',')
select Lambda.Wrap(() => {string u=s+s; return int.Parse(u);});
Update: To all people questioning this solution, look at Onkelborg’s answer to see what it would take to include the lambda without Lambda.Wrap() (while still maintaining query syntax). Please do not eliminate the lambda. This has to work for abitrary (value returning) lambdas. Also, I am looking for a query syntax solution, only. Please do not convert the expression to fluent syntax, thus trivializing it.
You can use the
letsyntax in your code:Alternately, you could use the LINQ extension methods directly instead of the special syntax:
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
Wrapdoes nothing because it’s the same asf():But if you do this,
fcan’t depend uponsin any way (for example, this way you can’t write your example code):What we’re really looking for is arbitrary closures over
s. For this to happen, the lambdas have to be defined inline, wheresis 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
letsyntax, 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 whatletis designed for! 🙂Alternately, you could just use lambdas which take parameters like
f2above.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 🙂