find the mode of a list of numbers in csharp

You can use LINQ to group the numbers by their frequency, and then get the group with the highest frequency as the mode. Here's the code:

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

public static double? GetMode(List<double> nums)
{
    if (nums == null || nums.Count == 0)
        return null;

    var groups = nums.GroupBy(x => x);

    var maxFrequency = groups.Max(g => g.Count());
    if (maxFrequency == 1)
        return null;

    var modes = groups.Where(g => g.Count() == maxFrequency)
                      .Select(g => g.Key);

    return modes.FirstOrDefault();
}
450 chars
20 lines

This method takes a List of double numbers as its input, and returns the mode as a Nullable<double>.

If the list is empty or null, the method returns null.

If there is no mode (i.e., all the numbers appear with equal frequency), the method also returns null.

Otherwise, it groups the numbers by their frequency and selects the group(s) with the highest frequency, and then returns the key (i.e., the number) of the first group. Note that there can be multiple modes if they occur with the same frequency, but this method returns only one of them.

gistlibby LogSnag