This post will discuss how to determine whether a collection has the same elements in C#, ignoring the total number of occurrences.

To compare two collections for equality when the total number of occurrences does not matter, we can take the help of the HashSet<T> collection.

Since HashSet<T> does not allow duplicate values, we can convert either collection to HashSet<T> and uses HashSet<T>.SetEquals() method to determine whether the HashSet<T> object and the other collection contain the same elements.

The following example compares two List<T> objects to each other using HashSet<T>.

Download  Run Code

 
We can also use LINQ’s Except() method, which returns unique elements in the first collection that don’t appear in the second collection. Here’s what the code would look like:

Download  Run Code

 
Another approach is to use LINQ’s All() method. This method checks if all unique elements in the first collection appeared in the second collection and vice versa.

Download  Run Code

That’s all about determining whether a collection has the same elements in C#.