CSharp - LINQ Average


The Average operator returns the average of numeric values contained in the elements of the input sequence.


There are two prototypes we cover. The First Average Prototype

public static Result Average(
  this IEnumerable<Numeric> source);

The Numeric type must be one of int, long, double, or decimal or one of their nullable equivalents, int?, long?, double?, or decimal?.

If the Numeric type is int or long, the Result type will be double.

If the Numeric type is int? or long?, the Result type will be double?.

Otherwise, the Result type will be the same as the Numeric type.

The first prototype of the Average operator returns an average of the elements themselves.

The second prototype of the Average operator determines the average for the member returned by the selector for every element.

public static Result Average<T>(
  this IEnumerable<T> source,
  Func<T, Numeric> selector);


  • ArgumentNullException is thrown if any argument is null.
  • OverflowException is thrown if the sum of the averaged values exceeds the capacity of a long for Numeric types int, int?, long, and long?.


using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from  w w  w .  j a va2s .c om
    static void Main(string[] args)
        IEnumerable<int> intSequence = Enumerable.Range(1, 10);
        Console.WriteLine("Here is our sequence of integers:");
        foreach (int i in intSequence)
        double average = intSequence.Average();
        Console.WriteLine("Here is the average:  {0}", average);


Related Topics