Check whether two lists have the same items in C#
This post will discuss how to check whether two lists have the same items in C#.
1. Using Enumerable.SequenceEqual Method
To determine if two lists are equal, ignoring the order, get a sorted copy of both lists and then compare them for equality with LINQ’s Enumerable.SequenceEqual method. It checks whether two sequences are of equal length and their corresponding elements are equal according to the default equality comparer for their type. This logic would translate to the following code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> first = new List<string>() { "A", "B", "C" }; List<string> second = new List<string>() { "C", "B", "A" }; bool isEqual = first.OrderBy(x => x).SequenceEqual(second.OrderBy(x => x)); Console.WriteLine(isEqual); // True } } |
2. Using Enumerable.All Method
To determine if two lists are equal, where frequency and relative order of the respective elements doesn’t matter, use the Enumerable.All method. It returns true if every element of the source sequence satisfy the specified predicate; false, otherwise. The following code example demonstrates the invocation of the Enumerable.All method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> first = new List<string>() { "A", "B", "C", "A", "C" }; List<string> second = new List<string>() { "A", "B", "B", "C" }; bool isEqual = first.All(second.Contains) && second.All(first.Contains); Console.WriteLine(isEqual); // True } } |
3. Using HashSet<T>.SetEquals Method
An alternative idea is to call the HashSet<T>.SetEquals method, which returns true if a HashSet object and the specified collection contain the same elements. However, this would need to convert any of the lists to set first. Note that this approach just checks if both lists contain the same elements in any order and in any frequency.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> first = new List<string>() { "A", "B", "C", "A", "C" }; List<string> second = new List<string>() { "A", "B", "B", "C" }; bool isEqual = first.ToHashSet().SetEquals(second); Console.WriteLine(isEqual); // True } } |
That’s all about checking whether two lists have the same items 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 :)