Aggregate Methods
Aggregate methods in LINQ provide an easy way to perform calculations over a sequence of elements. These methods allow you to compute sums, averages, and find maximum or minimum values from a collection. In this lesson, we will cover the commonly used aggregate methods in LINQ, how they work, and the caveats to watch out for, such as handling empty sets.
Aggregate Methods
Sum
The Sum
method calculates the sum of all elements in a collection. It works on collections of numeric types (integers, doubles, etc.).
Example
var numbers = new List<int> { 1, 2, 3, 4, 5 };
int totalSum = numbers.Sum(); // returns 15
Max/Min
Max
finds the maximum value in a collection.Min
finds the minimum value in a collection.
Example
var numbers = new List<int> { 1, 2, 3, 4, 5 };
int maxNumber = numbers.Max(); // returns 5
int minNumber = numbers.Min(); // returns 1
Average
The Average
method calculates the mean of a collection of numeric values.
var numbers = new List<int> { 1, 2, 3, 4, 5 };
double average = numbers.Average(); // returns 3
Exceptions with Empty Seats
When dealing with empty collections, aggregate methods such as Sum, Max, Min, and Average will throw an exception.
var emptyList = new List<int>();
int sumOfEmpty = emptyList.Sum(); // throws InvalidOperationException
Using DefaultIfEmpty
The DefaultIfEmpty method allows you to handle empty sequences gracefully by providing a default value. This is particularly useful with aggregate methods to avoid exceptions when dealing with empty collections.
var emptyList = new List<int>();
int safeSum = emptyList.DefaultIfEmpty(0).Sum(); // returns 0
int safeMax = emptyList.DefaultIfEmpty(0).Max(); // returns 0
//these would throw an exception:
int exceptional = emptyList.Sum();