CSharp - LINQ Average

Introduction

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

Prototypes

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);

Exceptions

  • 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?.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*  w  w w .ja v a 2s  . 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)
          Console.WriteLine(i);
        
        double average = intSequence.Average();
        Console.WriteLine("Here is the average:  {0}", average);
    }
}

Result

Related Topics