views:

112

answers:

2

Going thru one of my favourite authors question What’s the hardest or most misunderstood aspect of LINQ? I am basically looking for the answer of the question:

How the C# compiler treats query expressions

Thanks

A: 

The compiler will evaluate and transform your query expressions into the equivalent lambda syntax before compiling the code further. So code that starts as

 var query = from foo in foos 
             where foo.Bar == someString
             select new 
             {
                 Baz = foo.Baz,
                 Id = foo.Id
             };

Will be transformed into the lambda version

 var query = foos.Where(f => f.Bar == someString).Select(f => new { Baz = f.Baz, Id = f.Id });

The same will happen to your complicated joins, groupings, etc.

Anthony Pegram
But that's only half of the story, isn't it? The other half (at least for L2S) would be the transformation from lamba expression syntax to expression trees.
nikie
That other half would then be "how the C# compiler treats lambda expressions." I'll admit to really only thinking about this from a L2Objs perspective, though.
Anthony Pegram
A: 

The answer may vary between underlying LINQ providers.

Generally speaking, LINQ query expressions or method chains are transformed into Expression Tree before it goes to provider-specific implementation.

As for LINQ to Objects (IEnumerable), the expression tree is complied into a set of System.Func or System.Action delegates.

As for LINQ to SQL (IQueryable), the expression tree is transformed into T-SQL Statements.

Kthurein