Aggregate operators in LINQ
Wednesday, 24. December 2008, 21:23:51
1. Count
The Count operator counts the number of elements in a sequence.
public static int Count<T>( this IEnumerable<T> source); public static int Count<T>( this IEnumerable<T> source, Func<T, bool> predicate);
The Count operator without a predicate first checks whether the source sequence implements ICollection<T>. If so, the sequence’s implementation of ICollection<T> is used to obtain the element count. Otherwise, the source sequence is enumerated to count the number of elements.
The Count operator with a predicate enumerates the source sequence and counts the number of elements for which the predicate function returns true.
For both Count operators, an ArgumentNullException is thrown if any argument is null, and an OverflowException is thrown if the count exceeds int.MaxValue.
The following example returns the number of customers in London:
int count = customers.Count(c => c.City == "London");
2. LongCount
The LongCount operator counts the number of elements in a sequence.
public static long LongCount<T>( this IEnumerable<T> source); public static long LongCount<T>( this IEnumerable<T> source, Func<T, bool> predicate);
The LongCount operator enumerates the source sequence and counts the number of elements for which the predicate function returns true. If no predicate function is specified the LongCount operator simply counts all elements. The count of elements is returned as a value of type long.
For both Count operators, an ArgumentNullException is thrown if any argument is null.
3. Sum
The Sum operator computes the sum of a sequence of numeric values.
public static Numeric Sum( this IEnumerable<Numeric> source); public static Numeric Sum<T>( this IEnumerable<T> source, Func<T, Numeric> selector);
The Numeric type is one of int, int?, long, long?, double, double?, decimal, and decimal?.
The Sum operator enumerates the source sequence, invokes the selector function for each element, and computes the sum of the resulting values. If no selector function is specified, the sum of the elements themselves is computed. An ArgumentNullException is thrown if any argument is null. If the sum is too large to represent using the Numeric type, an OverflowException is thrown or, for double and double?, a positive or negative infinity is returned.
The Sum operator returns zero for an empty sequence. Furthermore, the operator does not include null values in the result (null values can occur when the Numeric type is a nullable type).
The following example produces a sequence of customer names and order totals for a given year:
int year = 2005;
var namesAndTotals =
customers.
Select(c => new {
c.Name,
TotalOrders =
c.Orders.
Where(o => o.OrderDate.Year == year).
Sum(o => o.Total)
});













