I have two lists A and B (List). How to determine if they are equal in the cheapest way? I can write something like '(A minus B) union (B minus A) = empty set' or join them together and count amount of elements, but it is rather expensive. Is there workaround?
If the ordering of the list items is relevant:
bool areEqual = a.SequenceEqual(b);
If the lists are to be treated as unordered sets:
// assumes that the list items are ints
bool areEqual = new HashSet<int>(a).SetEquals(b);
(The SequenceEqual
method and the HashSet<T>
constructor both have overloads that take an IEqualityComparer<T>
parameter, if you need that functionality.)
Well, that depends on how you interpret your lists.
If you consider them as tuples (so the order of elements in lists matters), then you can go with this code:
public bool AreEqual<T>(IList<T> A, IList<T> B)
{
if (A.Count != B.Count)
return false;
for (int i = 0; i < A.Count; i++)
if (!A[i].Equals(B[i]))
return false;
}
If you consider your lists as sets (so the order of elements doesn't matter), then... you are using the wrong data structures I guess:
public bool AreEqual<T>(IList<T> A, IList<T> B)
{
HashSet<T> setA = new HashSet<T>(A);
return setA.SetEquals(B);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With