using System.Collections.Generic;
public static class EnumerableExtensions
public static IEnumerable<T> GetMostFrequent<T>(this IEnumerable<T> inputs, int topXMostFrequent)
var uniqueGroups = inputs.GroupBy(i => i);
if (uniqueGroups.Count() == topXMostFrequent)
return uniqueGroups.Select(group => group.Key);
return uniqueGroups.OrderByDescending(i => i.Count())
.Select(group => group.Key);
public static void Main()
int[] numbers = { 1, 1, 1, 2, 2, 3 };
Console.WriteLine("Two most frequent numbers: " + string.Join(", ", numbers.GetMostFrequent(2)));
char[] letters = { 'a', 'a', 'a', 'b', 'b', 'c' };
Console.WriteLine("Two most frequent letters: " + string.Join(", ", letters.GetMostFrequent(2)));
string[] fruits = { "apple", "apple", "apple", "banana", "banana", "banana", "cherry", "cherry" };
Console.WriteLine("Two most common fruits: " + string.Join(", ", fruits.GetMostFrequent(2)));