Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set equality in linq

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?

like image 409
Alsin Avatar asked Jun 03 '09 14:06

Alsin


2 Answers

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.)

like image 183
LukeH Avatar answered Nov 09 '22 08:11

LukeH


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);
    }
like image 27
Max Galkin Avatar answered Nov 09 '22 10:11

Max Galkin