Check whether two lists have the same items in C#

Google Translate Icon

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:

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

That’s all about checking whether two lists have the same items in C#.

Rate this post

Average rating 4.65/5. Vote count: 17

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?




Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)



Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Do NOT follow this link or you will be banned from the site!