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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 21, 2023 (edit).