EditHow to write Queries
There are two styles for writing LINQ queries, until this point we have been using the Query Expression syntax, but you need to understand both to fully utilize the query operators made available to you -
1. Query Expression format (preferred) See:
Query Expression Syntaxint[] nums = new int[] {0,4,2,6,3,8,3,1};
var result = from n in nums
where n < 5
orderby n
select n;
2. Extension Method format (also known as the Dot Notation syntax) See:
Extension Method Syntaxint[] nums = new int[] {0,4,2,6,3,8,3,1};
var result = nums
.Where(n => n < 5)
.OrderBy (n => n);
Or when written on one line to better show Extension Methods at their best:
var result = nums.Where(n => n < 5).OrderBy (n => n);
3. A combination of the two formats, known as the Query Dot syntax. A Query Expression syntax query surrounded by parenthesis, followed by the dot notation Extension Method syntax. As long as the Query Expression returns an IEnumerable
, it can be followed by an Extension Method chain.
int[] nums = new int[] {0,4,2,6,3,8,3,1};
var result = (from n in nums
where n < 5
orderby n
select n).Distinct();
The Query Expression syntax has been designed to make writing queries more user-friendly and dare I say SQL like. The C# compiler converts all queries to use Extension Methods (although you don’t need to know that), so Query Expressions are solely there to make the developer experience that extra bit easier and it is a much cleaner syntax when you start to join and group.
My advice is use the Query Expression syntax wherever possible. I say “possible,” because the Query Expression syntax doesn’t support every Standard Query Operator currently available, and nor can it support any query operators you add over time. Drop back to the Query Dot syntax in those cases.