This post will discuss how to find all duplicates in an array in C#.

1. Using Enumerable.GroupBy Method

The idea is to group the elements based on their value and then filter the groups that appear more than once. This can be done with LINQ’s Enumerable.GroupBy() method.

The following example shows how to use GroupBy to find all repeated values in an array.

Download  Run Code

 
To get the frequency of the repeated elements, you can map each element of the group to have the properties Item and Count. For example,

Download  Run Code

Output:

{ Item = 2, Count = 3 }
{ Item = 4, Count = 2 }

 
Alternatively, you can construct a Dictionary<TKey,TValue> from an IEnumerable<T> with the Enumerable.ToDictionary() method.

Download  Run Code

Output:

[2, 3], [4, 2]

2. Using HashSet

Another option is to iterate over elements in the array and insert each element in a HashSet. If the current element already exists in the set, then it is a duplicate. This is demonstrated below:

Download  Run Code

3. Using Enumerable.Distinct Method

If you need to check the presence of only duplicate elements in the array, remove duplicate elements from it, and get the size of the result set. The Enumerable.Distinct method returns distinct elements from the sequence.

Download  Run Code

Output:

Array contains duplicates

That’s all about finding duplicates in an array in C#.