EditQuery Expression Format
The query expression syntax is much gentler than the Expression Method syntax and simplifies writing LINQ queries by removing Lambda Expressions and by using a familiar SQL like representation. One initial stumbling block to learning the LINQ syntax is that it reverses the Select-From-Where SQL structure and introduces From-Where-Select. There is good reason for this switch in keyword ordering; it allows better intellisense support where Visual Studio can offer assistance by displaying collection and properties whilst the developer is creating the query.
The basic form of the Query Expression is -
from [identifier] in [source collection]
let [expression]
where [boolean expression]
order by [[expression](ascending/descending)], [optionally repeat]
select [expression]
group [expression] by [expression] into [expression]
Figure - Query Expression simplified form
The full syntax can be found in (C# 3.0 Language Specification). Each query begins with a from keyword and ends with either a select or group by. To demonstrate the Query Expression syntax we’ll look at some examples (compare these to the syntax in
Extension Method Query Syntax.
List<Contacts> contacts = Contacts.SampleData();
var q = from c in contacts
where c.State == "WA"
orderby c.LastName, c.FirstName
select c;
foreach(Contacts c in q)
Console.WriteLine("{0} {1}", c.FirstName, c.LastName);
Figure - Query Expression syntax.
The following example query gets all contacts in the state of "WA" ordered by last name, then first name
List<Contacts> contacts = Contacts.SampleData();
List<CallLog> callLog = CallLog.SampleData();
var q = (from call in callLog
join contact in contacts on call.Number equals contact.Phone
orderby call.When descending
select new {contact.FirstName, contact.LastName,
call.When, call.Duration}).Take(5);
foreach(var call in q)
Console.WriteLine("{0} - {1} {2} ({3}min)",
call.When.ToString("ddMMM HH:m"),
call.FirstName, call.LastName, call.Duration);
Figure - Query Expression make Joins much simpler.
This query mixes the Extension Method syntax and Query where a Standard Query Operator isn’t supported (in this case the .Take method). This is because the Query Expression return type in an IEnumerable
, we can use any of the Standard Query Operators as straight extension methods.
Developer Tips –
• Use the Query Expression syntax wherever possible, its easier to read;
• If you need to mix the Extension Methods with Query Expressions, put them at the end;
• Keep each part of the Query Expression on separate lines to allow you to individually comment out an individual clause for debugging.