Home
C#
Sum Method
This page was last reviewed on May 21, 2023.
Dot Net Perls
Sum. 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.
An example. 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.
Tip The method can be used on objects that implement IEnumerable with a type of decimal, double, int or long.
Part 1 The program declares an int array and populates it with 3 numbers, and then declares a List with the same numbers.
Part 2 Sum() is invoked on those 2 variable references. It loops over the values and returns the sum of the elements.
int Array
Part 3 The program writes the sums to the screen. It uses Console.WriteLine to do this.
Console.WriteLine
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
Selector. With the Sum extension, we can use a selector overload. We provide a lambda expression that transforms each value to another one.
Tip We change the value 2.5 to 100, and all other values to 1. We can special-case some values with the lambda.
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.
null
for
Info Sum() inserts a null check. It uses a foreach-loop, which can produce slower execution on value types.
foreach
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.
A review. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 21, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.