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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With