Query Expression Translation in C# 3.0 - C# 3.0 Expression Queries and LINQ

Query Expression Translation in C# 3.0 - C# 3.0 Expression Queries and LINQ

by David Hayden ( Microsoft MVP C# ), Filed: C# 3.0 Tutorials and Examples

 

I mentioned the other day that I watched the C# 3.0 video with Eric Lippert and Charlie Calvert where they were talking about getting the C# 3.0 Compiler to work with type inference as needed by LINQ:

I don't remember the actual snippet of C# code, but during the video Eric mentioned that query expressions were syntatical sugar:

 

var query =
    from c in listOfCustomers
    where c.City.Equals("Sarasota")
    select new {c.Name,c.City};

 

By this, he was referring to the fact that C# 3.0 breaks this query expression into method calls:

 

var query = listOfCustomers.Where(c =>
    c.City.Equals("Sarasota")).Select(c =>
    new {c.Name, c.City});

 

C# 3.0 calls the extension methods Where and Select for IEnumerable<T> classes. This of course just gives you the query, the actual execution of the query doesn't happen until you enumerate the query such as with ToList():

 

var customers = query.ToList();

 

So, that is the whole point of Query Expression Translation in C# 3.0 and why Query Expressions are referred to syntatical sugar in the video. There are really just a facade over extension or instance methods that are being called under the covers. The C# 3.0 specification says it best:

“The C# 3.0 language does not specify the exact execution semantics of query expressions. Rather, C# 3.0 translates query expressions into invocations of methods that adhere to the query expression pattern. Specifically, query expressions are translated into invocations of methods named Where, Select, SelectMany, OrderBy, OrderByDescending, ThenBy, ThenByDescending, and GroupBy that are expected to have particular signatures and result types, as described in §26.7.2. These methods can be instance methods of the object being queried or extension methods that are external to the object, and they implement the actual execution of the query.“

 

Source Feed: David Hayden ( Microsoft MVP C# )

Filed: C# 3.0 Tutorials and Examples

posted on Wednesday, December 13, 2006 4:19 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices