The current solution works in a specific context, but there is further room for potential error. Without sorting the list, we should not assume a specific order; even if we have set it up in that way. Unaccounted logic or later changes may alter the order in one of the lists, which results in a false negative when comparing the elements of each list using a single index value.
The solution is fairly simple. Just sort the list, before you compare values in it. This is straight forward, if we are using
int values already know how to sort themselves, in a list. If we ever want the same functionality from a
List<t> of custom types, we need to make use of the
System.IComparable<in t> interface.
We sort a
List<t> with the method
List<t>.Sort(). Sorting both lists before comparing values guarantees that if the lists both contain the same set of values, they will also be in the same order.
private bool DoListsMatch(List<int> list1, List<int> list2)
var areListsEqual = true;
if (list1.Count != list2.Count)
list1.Sort(); // Sort list one
list2.Sort(); // Sort list two
for (var i = 0; i < list1.Count; i++)
if (list2[i] != list1[i])
areListsEqual = false;
System.IComparable<in t> to make custom types compatible with
Should we want to perform the same function on a list that contains custom types, we need to add the
System.IComparable<in t> interface to that type. This interface only contains one method that needs to be implemented in the class -
public int CompareTo(t other). This method compares the local type with the
other type, and returns an
int value representing the the placement of the local type in comparison to the
For the example, I will simply use a custom class that stores an
int. You can set this
CompareTo() method up in any way you like, specific to the types you use inside that class. You may want to compare ID numbers, or compare distances to a particular position, or even a given name.
class MyInt : IComparable<MyInt>
public int CompareTo(MyInt other)
private bool DoListsMatch(List<MyInt> list1, List<MyInt> list2)
As a final note, with the use of a custom implementation of
int CompareTo(t other), it is worth considering the possibility of error if two unique
t values can still compare with each-other as equal. If the same two values would not return a value of
true when compared as
valueA == valueB1, there is still a possibility of incorrect output, when comparing both lists. If
CompareTo() returns a value of 0, the items will not sort in any particular order (in relation to eachother), in the list. As such, we can not guarantee the order of the list1.
1 If the two items also return
true when compared using the
== operator, the previous checks will still correctly identify the objects as equal, and this will be a non-event.