Calculate sum of all Dictionary values in C#
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("A", 1); dict.Add("B", 2); dict.Add("C", 3); dict.Add("D", 4); var total = dict.Sum(x => x.Value); Console.WriteLine(total); // 10 } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using System; using System.Collections.Generic; public static class Extensions { public static int SumOfValue<K>(this IDictionary<K,int> dict) { int total = 0; foreach (int value in dict.Values) { total += value; } return total; } } public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("A", 1); dict.Add("B", 2); dict.Add("C", 3); dict.Add("D", 4); var total = dict.SumOfValue(); Console.WriteLine(total); // 10 } } |
That’s all about calculating the sum of all Dictionary<TKey,TValue>
values in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)