Книга: C# 2008 Programmer

Aggregate Functions

Aggregate Functions

In an earlier section, you used the following query to obtain a list of authors living in CA:

var authors =
 from author in ds.Tables[0].AsEnumerable()
 where author.Field<string>("State") == "CA"
 select author;

To get the total number of authors living in CA, you can use the Count() extension method (also known as an aggregate function), like this:

Console.WriteLine(authors.Count());

A much more efficient way would be to use the following query in method syntax:

var query =
 ds.Tables[0].AsEnumerable().Count(a => a.Field<string>("State")=="CA");
Console.WriteLine(query);
 

LINQ supports the following standard aggregate functions:

Aggregate function Description
Aggregate Performs a custom aggregation operation on the values of a collection.
Average Calculates the average value of a collection of values.
Count Counts the elements in a collection, optionally only those elements that satisfy a predicate function.
LongCount Counts the elements in a large collection, optionally only those elements that satisfy a predicate function.
Max Determines the maximum value in a collection.
Min Determines the minimum value in a collection.
Sum Calculates the sum of the values in a collection.

For example, the following statements print out the largest odd number contained in the nums array:

int[] nums = {
 12, 34, 10, 3, 45, 6, 90, 22, 87, 49, 13, 32
};
var maxOddNums = nums.Where
 (n => n % 2 == 1).OrderByDescending(n => n).Max();
Console.WriteLine("Largest odd number: {0}", maxOddNums); //---87---

The following statements print out the sum of all the odd numbers in nums:

int[] nums = {
 12, 34, 10, 3, 45, 6, 90, 22, 87, 49, 13, 32
};
var sumOfOddNums = nums.Where
 (n => n % 2 == 1).OrderByDescending(n => n).Sum();
Console.WriteLine("Sum of all odd number: {0}", sumOfOddNums); //---197---

Оглавление книги


Генерация: 0.078. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз