C# Aggregates
An aggregate combines a whole sequence into one value. Count, Sum, and Average each read every item and return a single result.
Count with a predicate and Sum
Count takes a predicate that selects the even numbers. Sum adds every number in the list.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 5, 2, 8, 1, 9, 3 };
Console.WriteLine("Even count: " + numbers.Count(n => n % 2 == 0));
Console.WriteLine("Sum: " + numbers.Sum());
}
}Average, Min, and Max
Average combines these values into exactly 4. Min and Max read the ends of the range.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 3, 5, 7 };
Console.WriteLine("Average: " + numbers.Average());
Console.WriteLine("Min: " + numbers.Min());
Console.WriteLine("Max: " + numbers.Max());
}
}Any, All, and First
Any and All answer true or false questions about the list. First returns the first number above 5.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 4, 7, 9 };
Console.WriteLine("Has big: " + numbers.Any(n => n > 8));
Console.WriteLine("All positive: " + numbers.All(n => n > 0));
Console.WriteLine("First big: " + numbers.First(n => n > 5));
}
}First with no match
No number in this list is above 10. First throws an exception and the program stops.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3 };
int first = numbers.First(n => n > 10);
Console.WriteLine(first);
}
}Example
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> scores = new List<int> { 80, 90, 100 };
Console.WriteLine("Passing: " + scores.Count(s => s >= 90));
Console.WriteLine("Total: " + scores.Sum());
Console.WriteLine("Average: " + scores.Average());
}
}Key points
- Count with a predicate counts only the items that pass the test.
- Sum adds all the numbers in a sequence.
- Average returns a double, so clean data is chosen for its exhibits.
- Min returns the smallest value and Max returns the largest value.
- Any answers whether at least one item passes a test.
- All answers whether every item passes a test.
- First returns the first item that passes a test.
In this example, Count counts the scores of 90 or more. Sum adds the three scores into 270. Average divides that total by three and prints 90.
Note
First throws an exception when no item matches.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens when First finds no matching item?