.NET Technical bits: LINQ Queries - Method Syntax

Monday, May 10, 2010

LINQ Queries - Method Syntax

Some query operations must be expressed as a method call. The most common such methods are those that return singleton numeric values, such as Sum, Max, Min, Average, and so on. These methods must always be called last in any query because they represent only a single value and cannot serve as the source for an additional query operation. The following example shows a method call in a query expression:

List numbers1 = new List() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List numbers2 = new List() { 15, 14, 11, 13, 19, 18, 16, 17, 12, 10 };
// Query #4.
double average = numbers1.Average();

// Query #5.
IEnumerable concatenationQuery = numbers1.Concat(numbers2);


If the method has parameters, these are provided in the form of a lambda expression, as shown in the following example:

// Query #6.
IEnumerable largeNumbersQuery = numbers2.Where(c => c > 15);


In the previous queries, only Query #4 executes immediately. This is because it returns a single value, and not a generic IEnumerable<(Of <(T>)>) collection. The method itself has to use foreach in order to compute its value.
Each of the previous queries can be written by using implicit typing with var, as shown in the following example:

// var is used for convenience in these queries
var average = numbers1.Average();
var concatenationQuery = numbers1.Concat(numbers2);
var largeNumbersQuery = numbers2.Where(c => c > 15);

No comments:

Post a Comment