If we use LINQ query, we can count distinct elements in array in C# by following command:

int[] a = { 0,0,1,7,17,1,2,2,3 };

int count = a.Distinct().Count();

The other way to count distinct elements in array in C# if array is already sorted is to use following code:

int count = -1;
int no_repeats = 0;
for (int i = 0; i < a.Length – 1; i++)

if (a[i] == a[i + 1]) no_repeats ++;

count = a.Length – no_repeats;

So, it is not complicated and complexity is linear (O(N)) if array is already sorted.

Example how to make distinct list from non-distinct array:

string[] str_figures = new string[chr_figures.Length];
List<string> unique_figures = str_figures.Distinct().ToList();


External links:

Count Distinct Elements in Array in C# in Stackoverflow

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *