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

1
  • 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, 2010 at 12:15

2 Answers 2

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.

2
  • 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, 2010 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. Jun 18, 2010 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.