[LINQ Operators] Average

The “Average” operator calculates the average of a sequence of numeric values. You can provide the selector delegate instead of using the “Where” operator.


1. Sample Data Object

To test examples, you need to include the <data classes> in your project.


2. “Average” Operator

  • NonDeferred operator
  • Purpose: Aggregate


3. Prototypes

public static <NUMERICTYPE> Average(
  this IEnumerable<NUMERICTYPE> source)

public static Nullable<NUMERICTYPE> Average(
  this IEnumerable<Nullable<NUMERICTYPE>> source)

public static <NUMERICTYPE> Average(
  this IEnumerable<T> source,
  Func<T, NUMERICTYPE> selector)

public static Nullable<NUMERICTYPE> Average<T>(
  this IEnumerable<T> source,
  Func<T, Nullable<NUMERICTYPE>> selector)

The “NUMERICTYPE” can be int, long, double, or decimal. The return type is not the same as the input type unlike “Max” or “Min“.

  • If the input type is decimal, the return type is decimal too.
  • But if the input type is int, long, or double, the return type is double.


4. Example 1 (Standard Operator)

int[] nums = new int[] { 3, 9, 1, 2, 10, 4, 8, 7, 6, 5 };

double aveNum = nums.Average();
Console.WriteLine($"The average [1 .. 10]: {aveNum}"); // 5.5


5. Example 2 (Query Expression)

There’s no corresponding query expression for the “Average()” operator.


6. Example 3 (Standard Operator) – with a selector

new Food { Name="Bread", Price=3.99M },
new Food { Name="Coffee", Price=1.99M },
new Food { Name="Burger", Price=4.99M },
new Food { Name="Coke", Price=1.25M },
new Food { Name="Salad", Price=6.50M },
new Food { Name="Pizza", Price=8.99M },
new Food { Name="Special", Price=null }

IEnumerable<Food> foods = Food.GetFoods();

decimal avePriceWithNull = foods.Average(f => f.Price ?? 0M);
Console.WriteLine($"The average: {avePriceWithNull:0.00}"); // 3.96


IEnumerable foods = Food.GetFoods();

decimal? avePriceNoNull= foods.Average(f => f.Price);
Console.WriteLine($"The average: {avePriceNoNull ?? 0:0.00}"); // 4.62


You can see the average of the second example is bigger than that of the first example. It is because in the first example, null price is calculated as 0 (1 more item).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s