Find Distinct Values And Its Count From An Array


There are many problems, which we face as developers in our day to day life and we solve them but each of these problems can be solved in multiple ways and perform better in different scenarios.

I am discussing a simple problem of finding dupilcate numbers from an array and the count of repitition of the numbers in the array, using 2 approaches i.e. using Dictionary and LINQ.


Here, I will be solving the problem both, using LINQ and Dictionary. I will be capturing the performance as well by using stopwatch.

Using LINQ

I have used the piece of code given below to get to the result, using LINQ.

I have created an array of int in the example given above. It contains duplicate values and our aim is to find the distinct values and capture the no. of times those are appearing in the array. I have groupBy all the emements, followed by selecting the distinct items and the no of times; they are appearing on the array. 

The same opperation time is captured, using Stopwatch.

Using Dictionary

Same thing is achived, using Dictionary object also.

I have created Dictionary object of type <int, int> . Here, key is the distinct number and the values represents the count of times of the respective numbers, which are appearing in the array.


Following is the output, which I have received both the times.


Final output with performance check

I had created both as 2 different methods and called it from main method. I had stopwatches in both the methods to capture the time also. The final result is shown below. 


The winner is Dictionary.

You can easily see the difference is time taken for such small amount of records. The time difference between LINQ and Dictionary is huge. Thus, choose wisely before implementing some small changes as it might give you a nightmare in future.

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now