In this article, I explore various techniques for counting the occurrences of each number in C#, comparing their efficiency based on factors such as speed, memory usage, and ease of implementation. Understanding these different methods helps developers choose the most efficient approach for their specific use case. This is a common question in .NET developer interviews, where interviewers may ask for multiple approaches to solve the problem. I have provided examples for each method to demonstrate their implementation.

1. Using Dictionary<int, int>
int[] numbers = { 1, 2, 3, 4, 2, 2, 5, 6, 2, 3, 5, 5, 5 };
var numberCounts = new Dictionary<int, int>();
foreach (int number in numbers)
{
if (numberCounts.ContainsKey(number))
numberCounts[number]++;
else
numberCounts[number] = 1;
}
foreach (var pair in numberCounts)
Console.WriteLine($"Number {pair.Key} appears {pair.Value} times.");
Console.ReadLine();

2. Using LINQ’s GroupBy
int[] numbers = { 1, 2, 3, 4, 2, 2, 5, 6, 2, 3, 5, 5, 5 };
var counts = numbers.GroupBy(n => n)
.Select(g => new { Number = g.Key, Count = g.Count() });
foreach (var item in counts)
Console.WriteLine($"Number {item.Number} appears {item.Count} times.");

3. Using SortedDictionary<int, int>
int[] numbers = { 1, 2, 3, 4, 2, 2, 5, 6, 2, 3, 5, 5, 5 };
var numberCounts = new SortedDictionary<int, int>();
foreach (int number in numbers)
{
if (numberCounts.ContainsKey(number))
numberCounts[number]++;
else
numberCounts[number] = 1;
}
foreach (var pair in numberCounts)
Console.WriteLine($"Number {pair.Key} appears {pair.Value} times.");
Console.ReadLine();




Join the conversation! Your thoughts help the community grow.