Section 4.4. Query Expressions


4.4. Query Expressions

A LINQ query is called a query expression. Query expressions start with the keyword from, and are written using SQL-like query operators such as Select, Where, and OrderBy:

 using System.Query;  // import standard LINQ query operators // all doctors living in Chicago, sorted by last name, first name: var chicago = from d in doctors               where d.City == "Chicago"               orderby d.FamilyLastName, d.GivenFirstName               select d; foreach (var r in chicago)   System.Console.WriteLine("{0}, {1}", r.FamilyLastName, r.GivenFirstName); 

By default, you must import the namespace System.Query to gain access to the standard LINQ query operators.

As noted earlier, type inference is used to make query expressions easier to write and consume:

             var chicago = from d in doctors ... select d; foreach (var r in chicago) ... ; 

But what exactly is a query expression? What type is inferred for the variable chicago above? Consider SQL. In SQL, a select query is a declarative statement that operates on one or more tables, producing a table. In LINQ, a query expression is a declarative expression operating on one or more IEnumerable objects, returning an IEnumerable object. Thus, a query expression is an expression of iteration across one or more objects, producing an object over which you iterate to collect the result. For example, let's be type-specific in our previous declaration:

             IEnumerable<Doctor> chicago = from d in doctors ... select d; 

LINQ defines query expressions in terms of IEnumerable<T> to hide implementation details (preserving flexibility!) while conveying in a strongly-typed way the key concept that a query expression can be iterated across:

 foreach (Doctor d in chicago) ... ; 

Of course, type inference conveniently hides this level of detail without any loss of safety or performance.



LINQ[c] The Future of Data Access in C# 3. 0
LINQ[c] The Future of Data Access in C# 3. 0
ISBN: N/A
EAN: N/A
Year: 2006
Pages: 25

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net