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.
![Ways to Count Occurrences of a each number in Array or List]()
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();
![Using Dictionary]()
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.");
![Using LINQ’s GroupBy]()
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();
![SortedDictionary]()
4. Using LINQ with ToLookup
int[] numbers = { 1, 2, 3, 2, 1, 3, 4, 1, 2, 3, 4, 4, 4 };
var numberCounts = numbers.ToLookup(n => n);
foreach (var group in numberCounts)
{
Console.WriteLine($"Number {group.Key} appears {group.Count()} times.");
}
Console.ReadLine();
![LINQ with ToLookup]()
5. Using List<Tuple<int, int>>
int[] numbers = { 1, 2, 3, 2, 1, 3, 4, 1, 2, 3, 4, 4, 4 };
List<Tuple<int, int>> numberCounts = new List<Tuple<int, int>>();
foreach (int num in numbers)
{
var index = numberCounts.FindIndex(t => t.Item1 == num);
if (index >= 0)
{
numberCounts[index] = Tuple.Create(num, numberCounts[index].Item2 + 1);
}
else
{
numberCounts.Add(Tuple.Create(num, 1));
}
}
foreach (var pair in numberCounts)
{
Console.WriteLine($"Number {pair.Item1} appears {pair.Item2} times.");
}
Console.ReadLine();
![Using List<Tuple<int, int>>]()
Best Choices for Most Cases:
✅ Dictionary – Best overall performance.
✅ LINQ GroupBy – Cleanest code if performance isn't the top priority.
Summary
In this article, we have explored various ways to find the number of occurrences in an array in C#. We have explored dictionary, Linq groupby, sorteddictionery, linq tolookup, and List<Tuple<int, int>>.
The article also highlights how these methods can be useful in .NET developer interviews, where candidates may be asked to demonstrate various solutions. Each approach is explained with examples to help developers understand and implement the most efficient solution for their needs.
If you wish to read more articles, please View My Articles
- Implement a retry policy in .NET 6 Applications with Polly
- Working with JSON in .NET Core: Newtonsoft.Json, NetJSON, and System.Text.Json
- Simplify Your Code with Switch Expressions: Patterns and Examples
- Understanding Model Binding in ASP.NET Core with .NET 8
- Difference Between =, == And === In JavaScript
Thank you for reading! I hope it was helpful. Please feel free to leave a comment and reach out if you have any questions.