find the mode of all keys in a map in csharp

To find the mode of all keys in a dictionary or map in C#, we can use LINQ and group the keys by their occurrence count:

main.cs
using System.Linq;

// initialize dictionary
Dictionary<int, string> dict = new Dictionary<int, string> { { 1, "apple" }, { 2, "banana" }, { 3, "cherry" }, { 4, "apple" }, { 5, "banana" }, { 6, "banana" } };

// group keys by occurrence count
var groupCounts = dict.GroupBy(x => x.Key)
                      .GroupBy(x => x.Count());

// find the highest occurrence count
int modeCount = groupCounts.Max(x => x.Key);

// get the keys with the highest occurrence count
var modeKeys = groupCounts.First(x => x.Key == modeCount)
                         .Select(x => x.Key);

// output the mode keys
foreach (int key in modeKeys)
{
    Console.WriteLine($"Mode key: {key}");
}
674 chars
22 lines

In this example, we initialize a dictionary with some key-value pairs, and then use LINQ to group the keys by their occurrence count. We then find the highest occurrence count and get the keys with that count, which represents the mode keys. Finally, we output the mode keys using a foreach loop.

related categories

gistlibby LogSnag