Reputation: 25927
For the sake of simplicity I pass along sets as IEnumerable
. I need to check, whether two such sets are equal. Currently I'm doing it in the following way:
if (theirs.OrderBy(t => t).SequenceEquals(mine.OrderBy(t => t)))
// equal
Is there a simpler way?
I need this code mainly for series of such comparisons:
if (mine."equals"(new[] { a, b })
{
do sth
}
else if (mine."equals"(new[] { a, c })
{
do sth
}
else if (mine.contains(a))
{
do sth
}
...
Upvotes: 0
Views: 204
Reputation: 1502526
If you could actually keep one of them as an ISet<T>
, you can just call SetEquals
. You could do this optionally, of course:
ISet<Foo> setFoo = theirs as ISet<Foo>;
if (setFoo != null && theirs.SetEquals(mine))
{
...
}
// Not a set? Use the slower approach
You don't have to sort the set though - you could do:
if (new HashSet<Foo>(theirs).SetEquals(mine))
for example. As noted in comments, this will treat { 1, 1, 2 } as equal to { 1, 2, 2 } though. Only use set operations if you really have a logical set.
Upvotes: 2