find the mode of all elements in an array in csharp

To find the mode of an array in C#, we can use LINQ to group the elements by their values and then order the groups by the count of their elements in descending order. We can then take the first group and return its key as the mode.

main.cs
public static int FindMode(int[] array)
{
    var groups = array.GroupBy(x => x).OrderByDescending(g => g.Count());
    return groups.First().Key;
}
149 chars
6 lines

Here, we define a static method FindMode that takes an int array as input and returns an int value. We use the GroupBy method of LINQ to group the array elements by their values. The result is a sequence of groups, where each group has a key (the value of the element that the group represents) and a collection of elements (the elements in the array that have that value).

We then use the OrderByDescending method to sort the groups by the count of their elements in descending order. This means that the group with the most elements will be first in the sequence.

Finally, we use the First method to get the first group in the sequence (i.e., the one with the most elements) and return its key as the mode.

Note that if there is a tie for the most common value, this will only return one of the modes. Depending on your requirements, you might want to modify the method to return a collection of modes instead.

gistlibby LogSnag