Aggregate functions help you quickly get useful information from a list of numbers or items, like counting how many there are, adding them up, or finding the average.
0
0
Aggregate functions (Count, Sum, Average) in C Sharp (C#)
Introduction
Counting how many students passed an exam from a list of scores.
Adding up all sales amounts to find total sales in a day.
Calculating the average temperature from daily readings.
Finding how many products are in stock from a product list.
Syntax
C Sharp (C#)
var count = collection.Count(); var sum = collection.Sum(x => x.Property); var average = collection.Average(x => x.Property);
These functions are part of LINQ and work on collections like arrays or lists.
You can use a lambda expression to specify which property to use for Sum and Average.
Examples
Count, Sum, and Average used directly on an array of numbers.
C Sharp (C#)
int[] numbers = {1, 2, 3, 4, 5}; int count = numbers.Count(); int sum = numbers.Sum(); double average = numbers.Average();
Using Count, Sum, and Average on a list of objects with a Score property.
C Sharp (C#)
var students = new List<Student> { new Student { Name = "Anna", Score = 80 }, new Student { Name = "Ben", Score = 90 }, new Student { Name = "Cara", Score = 70 } }; int count = students.Count(); int totalScore = students.Sum(s => s.Score); double avgScore = students.Average(s => s.Score);
Sample Program
This program creates a list of students with scores, then uses Count, Sum, and Average to find how many students there are, the total of their scores, and the average score. It prints these results.
C Sharp (C#)
using System; using System.Collections.Generic; using System.Linq; class Student { public string Name { get; set; } public int Score { get; set; } } class Program { static void Main() { var students = new List<Student> { new Student { Name = "Anna", Score = 80 }, new Student { Name = "Ben", Score = 90 }, new Student { Name = "Cara", Score = 70 } }; int count = students.Count(); int totalScore = students.Sum(s => s.Score); double averageScore = students.Average(s => s.Score); Console.WriteLine($"Number of students: {count}"); Console.WriteLine($"Total score: {totalScore}"); Console.WriteLine($"Average score: {averageScore:F2}"); } }
OutputSuccess
Important Notes
Count() returns the number of items in the collection.
Sum() adds up all values you specify.
Average() calculates the mean value and returns a double.
Summary
Use Count to find how many items are in a list.
Use Sum to add up values from a list.
Use Average to find the mean value from a list.