Possible Duplicate:
Test whether two IEnumerable<T> have the same values with the same frequencies
I wrote
UPDATED - correction:
static bool HaveSameItems<T>(this IEnumerable<T> self, IEnumerable<T> other)
{
return !
(
other.Except(this).Any() ||
this.Except(other).Any()
);
}
Isn't there a shorter way?
I know there is SequenceEqual
but the order doesn't matter for me.
Even if the order doesn't matter to you, it doesn't rule out SequenceEqual as a viable option.
var lst1 = new [] { 2,2,2,2 };
var lst2 = new [] { 2,3,4,5 };
var lst3 = new [] { 5,4,3,2 };
//your current function which will return true
//when you compare lst1 and lst2, even though
//lst1 is just a subset of lst2 and is not actually equal
//as mentioned by Wim Coenen
(lst1.Count() == lst2.Count() &&
!lst1.Except(lst2).Any()); //incorrectly returns true
//this also only checks to see if one list is a subset of another
//also mentioned by Wim Coenen
lst1.Intersect(lst2).Any(); //incorrectly returns true
//So even if order doesn't matter, you can make it matter just for
//the equality check like so:
lst1.OrderBy(x => x).SequenceEqual(lst2.OrderBy(x => x)); //correctly returns false
lst3.OrderBy(x => x).SequenceEqual(lst2.OrderBy(x => x)); // correctly returns true
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