C# Language Sum


The Enumerable.Sum extension method calculates the sum of numeric values.

In case the collection's elements are themselves numbers, you can calculate the sum directly.

int[] numbers = new int[] { 1, 4, 6 };
Console.WriteLine( numbers.Sum() ); //outputs 11

In case the type of the elements is a complex type, you can use a lambda expression to specify the value that should be calculated:

var totalMonthlySalary = employees.Sum( employee => employee.MonthlySalary );

Sum extension method can calculate with the following types:

  • Int32
  • Int64
  • Single
  • Double
  • Decimal

In case your collection contains nullable types, you can use the null-coalescing operator to set a default value for null elements:

int?[] numbers = new int?[] { 1, null, 6 };
Console.WriteLine( numbers.Sum( number => number ?? 0 ) ); //outputs 7