This post will discuss how to calculate the sum of all values in a Dictionary<TKey,TValue> in C#.

1. Using Enumerable.Sum() Method

A simple solution is to compute the sum of all values in a Dictionary is using the built-in numeric aggregation method Sum() from LINQ. The following code example demonstrates its usage.

Download  Run Code

2. Using foreach loop

If you don’t want to use LINQ, you can just iterate through the Dictionary using a foreach loop and sum up all values. This would translate to a simple code below:

Download  Run Code

That’s all about calculating the sum of all Dictionary<TKey,TValue> values in C#.