LINQ Aggregate Operators


Aggregate operators are used to perform operations on a collection of data to produce a single result. These operations typically involve combining or summarizing the elements of a collection. In LINQ and similar query languages, aggregate operators are powerful tools for data manipulation.

Here is an overview of common aggregate operators.

  1. Sum
  2. Average
  3. Min
  4. Max
  5. Aggregate

1. Sum

It calculates the sum of a numeric collection or a specified property of a collection of objects. Use Sum to get the total of all elements or a particular property in a collection.

Example

var numbers = new List<int> { 1, 2, 3, 4, 5 };
int total = numbers.Sum(); // Returns 15

var items = new List<Product> { new Product { Price = 10 }, new Product { Price = 20 } };
int totalPrice = items.Sum(item => item.Price); // Returns 30

2. Average

Calculates the average of a numeric collection or a specified property of a collection of objects. Use Average to find the mean value of all elements or a particular property.

Example

var numbers = new List<int> { 1, 2, 3, 4, 5 };
double average = numbers.Average(); // Returns 3

var items = new List<Product> { new Product { Price = 10 }, new Product { Price = 20 } };
double averagePrice = items.Average(item => item.Price); // Returns 15								

3. Min

It finds the minimum value in a numeric collection or a specified property of a collection of objects. Use Min to get the smallest value from all elements or a specific property.

Example

var numbers = new List<int> { 1, 2, 3, 4, 5 };
int min = numbers.Min(); // Returns 1

var items = new List<Product> { new Product { Price = 10 }, new Product { Price = 20 } };
int minPrice = items.Min(item => item.Price); // Returns 10

4. Max

It finds the maximum value in a numeric collection or a specified property of a collection of objects. Use Max to get the largest value from all elements or a specific property.

Example

var numbers = new List<int> { 1, 2, 3, 4, 5 };
int max = numbers.Max(); // Returns 5

var items = new List<Product> { new Product { Price = 10 }, new Product { Price = 20 } };
int maxPrice = items.Max(item => item.Price); // Returns 20

5. Aggregate

It applies a function cumulatively to the elements of a collection, optionally using an initial seed value, to produce a single result. Use Aggregate for custom aggregation logic that combines elements in a specific way.

Example

var numbers = new List<int> { 1, 2, 3, 4, 5 };
int product = numbers.Aggregate((total, next) => total * next); // Returns 120 (1*2*3*4*5)

// With seed value
int sumWithSeed = numbers.Aggregate(10, (total, next) => total + next); // Returns 25 (10 + 1 + 2 + 3 + 4 + 5)

Prev Next