What is the shortest way to compare if two IEnumerable<T> have the same items in C#? [duplicate]
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.Exce开发者_如何学JAVApt(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
Here's an O(n)
solution that only walks each sequence once (in fact, it might not even completely walk the second sequence, it has early termination possibilities):
public static bool HaveSameItems<T>(IEnumerable<T> a, IEnumerable<T> b) {
var dictionary = a.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
foreach(var item in b) {
int value;
if (!dictionary.TryGetValue(item, out value)) {
return false;
}
if (value == 0) {
return false;
}
dictionary[item] -= 1;
}
return dictionary.All(x => x.Value == 0);
}
One downside to this solution is that it's not going to interop with LINQ to SQL, EF, NHiberate etc. nicely.
精彩评论