HomeSearch

C# Sum Method: Add up All Numbers

Use the Sum extension method and the selector overload. Include the System.Linq namespace.

Sum.

This method adds up all values in an IEnumerable. It computes the sum total of all the numbers in an array, or List, of integers. This extension method in LINQ provides an excellent way to do this with minimal calling code.LINQ

Example.

The Sum method described here does not exist on either the array abstract base class or the List type. It is instead an extension method found in the System.Linq namespace, which you must include with a using directive.

Tip: The method can be used on objects that implement IEnumerable with a type of decimal, double, int or long.

Example: The program declares an int array and populates it with 4 odd numbers, and then declares a List with the same numbers.

Sum: Sum() is invoked on those 2 variable references. It loops over the values and returns the sum of the elements.

Int Array

Finally: The program writes the sums to the screen. It uses Console.WriteLine to do this.

Console.WriteLine
C# program that uses Sum 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 16 16

Selector.

With the Sum extension, we can use a selector overload. We provide a lambda expression that transforms each value to another one. Here we change the value 2.5 to 100, and all other values to 1.
C# program that uses Sum selector using System; using System.Linq; class Program { static void Main() { var numbers = new double[] { 2.5, 5.0 }; // Use ternary in Sum selector. // ... If 2.5, add 100. // Otherwise add just 1. var result = numbers.Sum(x => x == 2.5 ? 100 : 1); Console.WriteLine(result); } } Output 101

Discussion.

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.NullFor

Also: It uses a foreach-loop, which can produce slower execution on value types.

Foreach

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. This could be preferable.

Summary.

You can use the Sum extension method 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.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.