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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
becomes:
(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 ofEnumerable/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.