C# Language LINQ Queries Sum

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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


Got any C# Language Question?