Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is 'from/where/select' keywords impemented under the hood in LINQ and C#?

Tags:

c#

.net

linq

When I type 'from' (in a LINQ query) after importing System.Linq namespace, it is understood as a keyword. How does this magic happen?

Is 'from' a extension method on some type?

like image 755
Krishna Kumar Avatar asked Oct 10 '08 11:10

Krishna Kumar


1 Answers

In practice, yes - LINQ keywords map to extension methods. But actually, it is more interesting; it is literally as though the compiler substitutes directly for a few key methods, i.e.

var qry = from cust in db.Customers
          where cust.IsActive
          select cust;

becomes:

var qry = db.Customers.Where(cust => cust.IsActive);

(if we had a non-trivial select, it would add .Select(...some projection...)

Different LINQ kewords map to different methods - i.e. there is OrderBy, GroupBy, ThenBy, OrderByDescending, etc.

In the case of IEnumerable<T>/IQueryable<T>, this then resolves these via extension methods (typically courtesy of Enumerable/Queryable)- however, if your queryable objects declared their own Where/OrderBy/etc then these would get used in preference.

Jon Skeet covers this a lot more in the latter parts of C# in Depth. I've also seen an example of Jon's where he discusses some really bizarre implications of this - such as calling static methods on a type.

like image 70
Marc Gravell Avatar answered Oct 13 '22 00:10

Marc Gravell