How to insert lambda into Linq declarative query expression

Say you have the following code:

  string encoded="9,8,5,4,9";

  // Parse the encoded string into a collection of numbers
  var nums=from string s in encoded.Split(',')
           select int.Parse(s);

It's easy, but what if I want to apply a lambda expression to s in select, but still save it as a declarative query expression, in other words:

  string encoded="9,8,5,4,9";

  // Parse the encoded string into a collection of numbers
  var nums=from string s in encoded.Split(',')
           select (s => {/* do something more complex with s and return an int */});

This, of course, does not compile. But, how can I get lambda there without switching it to free syntax.

Update : thanks to the StriplingWarrior tutorial, I have a confusing but compiled solution:

var result=from string s in test.Split(',')
           select ((Func<int>) 
             (() => {string u="1"+s+"2"; return int.Parse(u);}))();

Func<string,int>, select (s). - - (.. Func, , , - , )?

. . , .

2: , , , ( ?) :

public static class Lambda
{
  public static U Wrap<U>(Func<U> f)
  {
    return f();
  }
}
... 
  // Then in some function, in some class, in a galaxy far far away:

  // Look what we can do with no casts
  var res=from string s in test.Split(',')
          select Lambda.Wrap(() => {string u="1"+s+"2"; return int.Parse(u);});

, . - Lambda.Wrap, - .NET 4.0, ? , : Wrap .NET 4.0.

+5
5

, LINQ , :

select DoSomethingComplex(s)

, Func:

Func<string, string> f = s => { Console.WriteLine(s); return s; };
var q = from string s in new[]{"1","2"}
        select f(s);

, , - :

from string s in new[]{"1","2"}
select ((Func<string>)(() => { Console.WriteLine(s); return s; }))()
+2

:

var nums = from string s in encoded.Split(',')
           select (s => { DoSomething(); return aValueBasedOnS; });

.

0

:

var nums= (from string s in encoded.Split(',') select s).Select( W => ...);
0

- - ?

. -,

var result = from s in encoded.Split(',')
             select ((Func<int>)(() => int.Parse("1" + s + "2")))();

However, this is not very readable, especially for query expression. You can use the keyword for this particular query and projection let.

var result = from s in encoded.Split(',')
             let t = "1" + s + "2"
             select int.Parse(t);
0
source

IEnumerable integers = encoded.Split (','). Select (s => int.Parse (s));

Edit:

IEnumerable<int> integers = from s in encoded.Split(',') select int.Parse(string.Format("1{0}2",s));
0
source

All Articles