tags:

views:

196

answers:

1

I am a beginner in Linq.

How can I rewrite this lambda expression as a linq compiled query?

var query5 = CustomerList.Select((cust, index) =>  new {cust, index})
                         .Where(c =>  c.cust.Country == "USA"  &&  c.index  >  70)
                         .Select(c =>  new { c.cust.CustomerID, c.cust.CompanyName, 
                                            c.index });

like

var query5 = from c in .......
             where .....
             select c new {....}
+5  A: 

Well here's the closest query expression syntax:

var query5 = from c in CustomerList.Select((cust, index) =>  new {cust, index})
             where c.cust.Country == "USA"  &&  c.index  >  70
             select new { c.cust.CustomerID, c.cust.CompanyName, c.index };

Basically the one bit you can't do in query expression syntax is the "select including the index" overload. There simply isn't any syntax which translates to that. (The same goes for quite a few other operations - VB's LINQ syntax is richer in this respect, although personally I'm happy with the way that C# does it; it avoids adding too many contextual keywords.)

(As Mehrdad says, this isn't a "compiled" query. In fact the code will be compiled to exactly the same IL.)

Jon Skeet
Beat me by 3 seconds! Never mind.
Graham Clark
Wasn't aware of an overload that includes an index. Yet another linq mystery resolved :-D
Yannick M.