This post will discuss how to find the duplicate elements in a list in C#.

1. Using Enumerable.GroupBy() Method

The idea is to use the Enumerable.GroupBy() method to group the elements based on their value, then filter out the groups that appear more than once, and retrieve the duplicates keys. Here’s what the code would look like:

Download  Run Code

 
The code can be shortened using the Enumerable.SelectMany() method. However, to get all distinct duplicates, consider applying the Distinct() method to the resulting sequence.

Download  Run Code

 
To find the frequency of the repeated elements, you can map each element to contain Element and Count properties. This can be used to retrieve the desired information.

Download  Run Code

Output:

{ Element = 5, Count = 2 }, { Element = -1, Count = 2 }

 
Alternatively, if you need a dictionary with the duplicate element as a key and the duplicate element’s count as its value, do as follows:

Download  Run Code

 
To determine whether a container contains any duplicate values or not, you can use the Enumerable.Any() method. The following code example returns true if the source sequence contains duplicated elements; otherwise, false.

Download  Run Code

 
Alternatively, you can check if the count of all distinct elements is exactly 1. This can be done using the Enumerable.All() method.

Download  Run Code

2. Using Set

The idea here is to iterate over the list and keep track of all the items in a HashSet. If an item is encountered before, mark it as duplicate and report all duplicate items at the end of the loop.

Download  Run Code

That’s all about finding the duplicate elements in a list in C#.