.NET Technical bits: LINQ Queries - Query Syntax

Monday, May 10, 2010

LINQ Queries - Query Syntax

The recommended way to write most queries is to use query syntax to create query expressions. The following example shows three query expressions. The first query expression demonstrates how to filter or restrict results by applying conditions with a where clause. It returns all elements in the source sequence whose values are greater than 7 or less than 3. The second expression demonstrates how to order the returned results. The third expression demonstrates how to group results according to a key. This query returns two groups based on the first letter of the word.

// Query #1.
List numbers = new List() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

// The query variable can also be implicitly typed by using var
IEnumerable filteringQuery =
from num in numbers
where num < 3 || num > 7
select num;

// Query #2.
IEnumerable orderingQuery =
from num in numbers
where num < 3 || num > 7
orderby num ascending
select num;

// Query #3.
string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" };
IEnumerable<IGrouping> queryFoodGroups =
from item in groupingQuery
group item by item[0];

Note that the type of the queries is IEnumerable<(Of <(T>)>). All of these queries could be written using var as shown in the following example:
var query = from num in numbers...
In each previous example, the queries do not actually execute until you iterate over the query variable in a foreach statement.

No comments:

Post a Comment