CSharp - LINQ Sum

Introduction

The Sum operator returns the sum of numeric values contained in the elements of the input sequence.

Prototypes

There are two prototypes we cover.

The First Sum Prototype

public static Numeric Sum(
  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?.

The first prototype of the Sum operator returns the sum of each element in the source input sequence.

An empty sequence will return the sum of zero.

The Sum operator will not include null values in the result for Numeric types that are nullable.

The second prototype of the Sum operator sums the value selected from each element by the selector method delegate.

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

Exceptions

  • ArgumentNullException is thrown if any argument is null.
  • OverflowException is thrown if the sum is too large to be stored in the Numeric type if the Numeric type is other than decimal or decimal?. If the Numeric type is decimal or decimal?, a positive or negative infinity value is returned.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*w  ww.ja v  a  2  s .co  m*/
{
    static void Main(string[] args)
    {
      IEnumerable<int> ints = Enumerable.Range(1, 10);

      foreach (int i in ints)
        Console.WriteLine(i);

      int sum = ints.Sum();
      Console.WriteLine(sum);
    }
}

Result

Related Topics