How to Use LINQ Average in C# for Calculating Averages
Use the
Average() method from LINQ to calculate the average of numeric values in a collection. It works on arrays, lists, or any enumerable of numbers and returns the mean as a double. You can also use it with a selector function to average specific properties of objects.Syntax
The Average() method is called on a collection of numbers or objects. It can be used in two main ways:
- Without selector: Calculates average of numeric values directly.
- With selector: Calculates average of a numeric property from each object.
Example syntax:
var avg = collection.Average();
var avgProperty = collection.Average(item => item.Property);csharp
var avg = collection.Average(); var avgProperty = collection.Average(item => item.Property);
Example
This example shows how to calculate the average of numbers in an array and the average of a property in a list of objects.
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] numbers = { 10, 20, 30, 40, 50 }; double averageNumbers = numbers.Average(); Console.WriteLine($"Average of numbers: {averageNumbers}"); var students = new List<Student> { new Student { Name = "Alice", Score = 85 }, new Student { Name = "Bob", Score = 90 }, new Student { Name = "Charlie", Score = 78 } }; double averageScore = students.Average(s => s.Score); Console.WriteLine($"Average score: {averageScore}"); } } class Student { public string Name { get; set; } public int Score { get; set; } }
Output
Average of numbers: 30
Average score: 84.3333333333333
Common Pitfalls
Common mistakes when using Average() include:
- Calling
Average()on an empty collection causes anInvalidOperationException. - Using
Average()on non-numeric types without a selector will not compile. - Not handling
nullvalues in collections of nullable types can cause exceptions.
To avoid errors, check if the collection has elements before calling Average() or use DefaultIfEmpty() to provide a default value.
csharp
using System; using System.Linq; class Program { static void Main() { int[] empty = { }; // This will throw InvalidOperationException // double avgEmpty = empty.Average(); // Safe way: double avgSafe = empty.DefaultIfEmpty(0).Average(); Console.WriteLine($"Safe average of empty array: {avgSafe}"); } }
Output
Safe average of empty array: 0
Quick Reference
| Usage | Description |
|---|---|
| collection.Average() | Calculates average of numeric values in collection |
| collection.Average(item => item.Property) | Calculates average of a numeric property in objects |
| collection.DefaultIfEmpty(0).Average() | Calculates average safely on possibly empty collection |
| Throws InvalidOperationException | If collection is empty and no default is provided |
Key Takeaways
Use LINQ's Average() to easily calculate the mean of numeric collections.
Provide a selector function to average specific properties of objects.
Avoid calling Average() on empty collections without a default value to prevent exceptions.
Use DefaultIfEmpty() to supply a default value when collections might be empty.
Average() returns a double representing the mean value.