Determine if collection has same elements in C#
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>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> x = new List<int>() { 3, 5, 3, 2, 5, 7 }; List<int> y = new List<int>() { 3, 5, 3, 7, 3, 2, 2 }; bool isEqual = new HashSet<int>(x).SetEquals(y); if (isEqual) { Console.WriteLine("Both Sequences have same elements"); } else { Console.WriteLine("Both Sequences have different elements"); } } } /* Output: Both Sequences have same elements */ |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> x = new List<int>() { 3, 5, 3, 2, 5, 7 }; List<int> y = new List<int>() { 3, 5, 3, 7, 3, 2, 2 }; bool isEqual = !x.Except(y).Any() && !y.Except(x).Any(); if (isEqual) { Console.WriteLine("Both Sequences have same elements"); } else { Console.WriteLine("Both Sequences have different elements"); } } } /* Output: Both Sequences have same elements */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> x = new List<int>() { 3, 5, 3, 2, 7, 7 }; List<int> y = new List<int>() { 3, 5, 3, 3, 7, 2 }; bool isEqual = x.All(y.Contains) && y.All(x.Contains); if (isEqual) { Console.WriteLine("Both Sequences have same elements"); } else { Console.WriteLine("Both Sequences have different elements"); } } } /* Output: Both Sequences have same elements */ |
That’s all about determining whether a collection has the same elements in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)