This method adds up all values in an IEnumerable
. It computes the sum total of all the numbers in an IEnumerable
(like an array or List
).
This extension method in LINQ provides an excellent way to sum numbers with minimal calling code. By avoiding loops, we can reduce possible bugs.
Sum()
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.
IEnumerable
with a type of decimal, double
, int
or long.int
array and populates it with 3 numbers, and then declares a List
with the same numbers.Sum()
is invoked on those 2 variable references. It loops over the values and returns the sum of the elements.Console.WriteLine
to do this.using System; using System.Collections.Generic; using System.Linq; // Part 1: declare 2 collections of int elements. int[] array1 = { 1, 1, 2 }; List<int> list1 = new List<int>() { 1, 1, 2 }; // Part 2: use Sum extension on their elements. int sum1 = array1.Sum(); int sum2 = list1.Sum(); // Part 3: write results to screen. Console.WriteLine("SUM: {0}", sum1); Console.WriteLine("SUM: {0}", sum2);SUM: 4 SUM: 4
With the Sum extension, we can use a selector overload. We provide a lambda expression that transforms each value to another one.
using System; using System.Linq; 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);101
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.
Sum()
inserts a null
check. It uses a foreach
-loop, which can produce slower execution on value types.We avoid copying code into a program source and instead use code that is more tested. This may reduce the assembly's size. It will reduce the number of lines of C# code.
Sum()
totals 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.