Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Determine if two sequences contains exactly the same elements

Tags:

c#

.net

linq

I need to determine whether or not two sets contains exactly the same elements. The ordering does not matter.

For instance, these two arrays should be considered equal:

IEnumerable<int> data = new []{3, 5, 6, 9}; IEnumerable<int> otherData = new []{6, 5, 9, 3} 

One set cannot contain any elements, that are not in the other.

Can this be done using the built-in query operators? And what would be the most efficient way to implement it, considering that the number of elements could range from a few to hundreds?

like image 227
driis Avatar asked Nov 04 '09 11:11

driis


2 Answers

If you want to treat the arrays as "sets" and ignore order and duplicate items, you can use HashSet<T>.SetEquals method:

var isEqual = new HashSet<int>(first).SetEquals(second); 

Otherwise, your best bet is probably sorting both sequences in the same way and using SequenceEqual to compare them.

like image 53
mmx Avatar answered Nov 02 '22 09:11

mmx


I suggest sorting both, and doing an element-by-element comparison.

data.OrderBy(x => x).SequenceEqual(otherData.OrderBy(x => x)) 

I'm not sure how fast the implementation of OrderBy is, but if it's a O(n log n) sort like you'd expect the total algorithm is O(n log n) as well.

For some cases of data, you can improve on this by using a custom implementation of OrderBy that for example uses a counting sort, for O(n+k), with k the size of the range wherein the values lie.

like image 39
Joren Avatar answered Nov 02 '22 11:11

Joren