When I type 'from' (in Linq query) after improrting system.Linq namespace it is understood as a keyword; how does this magic hapen. is 'from' a extension method on some type?
"from" is a language keyword (just like "if" or "foreach").
You don't even need to import System.Linq to use "from", but you need to use 3.5 framework.
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.
Marc Gravell has answered the question admirably, but I can't resist the temptation to mention the weird things you can do with query expressions. The compiler really doesn't care very much how it finds a "Select" member, or "Where" etc.
The way that the compiler translates the code into "C# 3.0 without query expressions" before doing normal compilation is really beautiful - it's a wonderful way of introducing new functionality into the language but only having an impact in one isolated portion of the specification.