.NET Technical bits: LINQ - Mixed Query and Method Syntax

Monday, May 10, 2010

LINQ - Mixed Query and Method Syntax

This example shows how to use method syntax on the results of a query clause. Just enclose the query expression in parentheses, and then apply the dot operator and call the method. In the following example, query #7 returns a count of the numbers whose value is between 3 and 7. In general, however, it is better to use a second variable to store the result of the method call. In this manner, the query is less likely to be confused with the results of the query.

// Query #7.

// Using a query expression with method syntax
int numCount1 =
(from num in numbers1
where num < 3 || num > 7
select num).Count();

// Better: Create a new variable to store
// the method call result
IEnumerable numbersQuery =
from num in numbers1
where num < 3 || num > 7
select num;

int numCount2 = numbersQuery.Count();

Because Query #7 returns a single value and not a collection, the query executes immediately.
The previous query can be written by using implicit typing with var, as follows:

var numCount = (from num in numbers...
It can be written in method syntax as follows:
var numCount = numbers.Where(n => n < 3 || n > 7).Count();
It can be written by using explicit typing, as follows:
int numCount = numbers.Where(n => n < 3 || n > 7).Count();

No comments:

Post a Comment