Alex Rivera | Logout

set equality in linq

Asked 2009-06-03T14:37:52.603
10

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?

Edit
Report

2 Answers

1

It depends on what you mean by "the list are equal". If you mean they contain the same objects, the solution suggested by Daniel is fine, just Union() the two list and count the items.

If by "equal" you mean that they have the same items in the same order, you'd be better off comparing the Count of both lists, then if they have the same count, just iterate with a plain for loop to compare each element from both lists at the same index. Less pretty but you can hardly be faster.

answered 2009-06-03T14:47:43.783
-1

A first shot - if they contain the same items, the union of both list should have the same number of items as any of both lists.

listA.Union(listB).Count() == listA.Count()

Note: Fails if one list is empty.

But it's probably still a O(n²) operation.

Another solution - the lists must have the same length and list A minus list B must not contain any elements.

(listA.Count() == listB.Count()) && !listA.Except(listB).Any()
answered 2009-06-03T14:42:47.897

Your Answer