C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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 ArrayFinally: The program writes the sums to the screen. It uses Console.WriteLine to do this.
ConsoleC# 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
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
Also: It uses a foreach-loop, which can produce slower execution on value types.
Foreach