[LINQ Operators] Sum

The “Sum” operator calculates the sum of a sequence of numeric values.


1. Sample Data Objects

To test examples, you need to include the <data classes> in your project.


2. “Sum” operator

  • NonDeferred operator
  • Purpose: Aggregate


3. Prototypes

public static NUMERICTYPE Sum(
  this IEnumerable<NUMERICTYPE> source)

public static Nullable<NUMERICTYPE> Sum(
  this IEnumerable<Nullable<NUMERICTYPE>> source)

public static NUMERICTYPE Sum(
  this IEnumerable<T> source,
  Func<T, NUMERICTYPE> selector)

public static Nullable<NUMERICTYPE> Sum<T>(
  this IEnumerable<T> source,
  Func<T, Nullable<NUMERICTYPE>> selector)

The “NUMERICTYPE” can be int, long, double, or decimal. There are many overloaded “Sum()” operators but they do the same thing: returns the sum of numeric values .


4. Example 1 (Standard Operator)

int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int totalNum = nums.Sum();
Console.WriteLine($"The sum from 1 to 10: {totalNum}"); // 55


5. Example 2 (Query Expression)

There’s no corresponding query expression for the “Sum()” operator.


6. Example 3 (Standard Operator) – with a condition

IEnumerable<Food> foods = Food.GetFoods();

var specialFoods
  = foods.Where(f => (f.Name == "Special"));
decimal totalPrice = foods.Except(specialFoods).Sum(f => f.Price ?? 0M);
Console.WriteLine($"The total price: {totalPrice}"); // 27.71


The null values are ignored in the next example.

IEnumerable<Food> foods = Food.GetFoods();

decimal? totalPrice = foods.Sum(f => f.Price);
Console.WriteLine("The total price: {totalPrice ?? 0M}"); // 27.71

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s