System.Linq.Enumerable.Sum Method

Namespace: System.Linq
Assembly: System.Linq.dll

Computes the sum of a sequence of numeric values.

public static int Sum(IEnumerable<int>source)
public static long Sum(IEnumerable<long>source)
public static float Sum(IEnumerable<float>source)
public static double Sum(IEnumerable<double>source)
public static decimal Sum(IEnumerable<decimal>source)
public static TResult Sum<TSource, TResult>(IEnumerable<TSource>source, Func<TSource, TResult>selector)
public static TSource Sum<TSource>(IEnumerable<TSource>source)

Description

The Sum extension method calculates the sum of all elements in an enumerable collection of numeric types. It supports various numeric types like int, long, float, double, and decimal. Overloads are provided to directly sum sequences of these types or to project elements using a selector function before summing.

If the input sequence is empty, the method returns 0 for integral types and 0.0 for floating-point and decimal types. For generic overloads with a selector, an empty sequence will also result in the default value of the result type.

Parameters

Name Type Description
source IEnumerable<int>
IEnumerable<long>
IEnumerable<float>
IEnumerable<double>
IEnumerable<decimal>
IEnumerable<TSource>
An enumerable collection of numeric values to sum.
selector Func<TSource, TResult> A transform function to apply to each element.

Returns

The sum of the values in the sequence. If the sequence is empty, 0 is returned for integral types, 0.0 for floating-point and decimal types, or the default value of TResult for generic overloads.

Example

This example demonstrates how to use the Sum method to calculate the sum of integers in an array.


using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        int sum = numbers.Sum();

        Console.WriteLine("The sum of the numbers is: {0}", sum); // Output: The sum of the numbers is: 15

        string[] words = { "apple", "banana", "cherry" };

        int totalLength = words.Sum(word => word.Length);

        Console.WriteLine("The total length of the words is: {0}", totalLength); // Output: The total length of the words is: 16
    }
}