1

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

Community
  • 1
  • 1
Newbie
  • 1,111
  • 3
  • 17
  • 36
  • 2
    This is a bit broad of a question. In terms of what exactly? Or do you mean what do they end up being compiled as? – lc. Jun 18 '10 at 12:15

2 Answers2

0

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
  • 123,721
  • 27
  • 225
  • 246
  • 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. – Niki Jun 18 '10 at 14:04
  • 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 Jun 18 '10 at 14:19
0

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.

Thurein
  • 2,536
  • 7
  • 34
  • 49