find the sum of all keys in a map in csharp

You can use LINQ to sum the keys of a dictionary or a map in C#:

main.cs
using System.Linq;
using System.Collections.Generic;

Dictionary<int, int> map = new Dictionary<int, int>();
// Populate the map with some key-value pairs

int sum = map.Keys.Sum();

// Alternatively, you can use LINQ query syntax:
int sum = (from entry in map select entry.Key).Sum();
286 chars
11 lines

In this example, map is a Dictionary<int, int> representing a map with integer keys and values. The Keys property of the dictionary is an enumerable sequence of keys, which can be summed using the Sum method from the System.Linq namespace. Alternatively, you can use LINQ query syntax to select the keys from the dictionary and then sum them. Either way, the result is the sum of all keys in the map.

related categories

gistlibby LogSnag