find the mode of all values in a map in csharp

To find the mode (most frequently occurring value) of all the values in a Dictionary in C#, we can use LINQ to group and count the values, and then select the key with the highest count. Here's an example implementation:

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

public static TKey FindMode<TKey, TValue>(Dictionary<TKey, TValue> dictionary)
{
    var mode = dictionary.GroupBy(pair => pair.Value) // group by values
        .OrderByDescending(group => group.Count()) // order by count in descending order
        .FirstOrDefault(); // select first group (i.e. mode) or null if dictionary is empty
    return mode?.Key;
}
413 chars
11 lines

This method takes a dictionary as input and returns the key (i.e. the value) that appears most frequently in the dictionary. If there is a tie for the mode, the method will return the key that appears first in the dictionary.

Example usage:

main.cs
var dictionary = new Dictionary<int, string>
{
    { 1, "apple" },
    { 2, "banana" },
    { 3, "apple" },
    { 4, "cherry" },
    { 5, "banana" },
    { 6, "cherry" },
    { 7, "banana" },
    { 8, "apple" },
};

var mode = FindMode(dictionary); // returns "banana" (appears 3 times)
287 chars
14 lines

Note that this implementation assumes that the dictionary values are not null, and that the dictionary is not empty. You should add appropriate null checks and error handling as necessary in your own code.

gistlibby LogSnag