C# Sum Method

Dot Net Perls
Sum method

You want to compute the sum total of all the numbers in an array of integers or List of integers in the C# language. The Sum extension method in LINQ provides an excellent way to do this with minimal calling code, but has some drawbacks.

Example

The Sum method described here does not exist on either the array abstract base class or the List type, but instead is an extension method found in the System.Linq namespace, which you must include with a using directive. The method can be used on objects that implement IEnumerable with a type of decimal, double, int or long. This example sums an array and a List.

IEnumerable Decimal Examples Double Type Int Type Long
Program that uses Sum [C#]

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

class Program
{
    static void Main()
    {
	//
	// Declare two collections of int elements.
	//
	int[] array1 = { 1, 3, 5, 7 };
	List<int> list1 = new List<int>() { 1, 3, 5, 7 };

	//
	// Use Sum extension on their elements.
	//
	int sum1 = array1.Sum();
	int sum2 = list1.Sum();

	//
	// Write results to screen.
	//
	Console.WriteLine(sum1);
	Console.WriteLine(sum2);
    }
}

Output
    (All element values were added together to get the result.)

16
16

Overview. The program declares an array of integers and populates it with four odd numbers, and then declares a List instance with the same four odd numbers. The Sum extension method is invoked on those two variable references, which internally loops over the values and returns the sum of the elements. Finally, the program writes the sums to the screen.

Discussion

Note (please read)

There are drawbacks associated with the Sum extension method. The Sum method has some overhead that will make it slower than a simple for loop in the C# language. It inserts a null check at the start of its method body. Also, it uses a foreach loop, which can produce slower execution on value types.

Null Tips For Loops Foreach Loop Examples

Benefits. By using Sum, you avoid copying code into your program source and instead exploit code inside the framework that is more tested. This will reduce the assembly's code size and number of lines of C# code in your program. For very small arrays and Lists, this could be preferable.

Array Examples List Examples

Summary

.NET Framework information

We saw how you can use the Sum extension method from the System.Linq namespace in the C# language to total the values of elements in an array or List. We noted the implementation in the base class library of the Sum extension, as well as some overloads you can use. It provides a way for you to write less code that requires less thought to maintain, at the price of runtime performance, which may be less important.

LINQ Examples