比较两个List&LT; T&GT;平等的对象,无视秩序 [英] Compare two List<T> objects for equality, ignoring order
问题描述
另一个列表的比较问题。
Yet another list-comparing question.
List<MyType> list1;
List<MyType> list2;
我需要检查它们都具有相同的元素,无论在列表中的位置的。每个的MyType 对象可以在列表上出现多次。是否有一个内置的功能,它检查呢?如果我保证每一个元素在列表中只出现一次?
I need to check that they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list. Is there a built-in function that checks this? What if I guarantee that each element appears only once in a list?
编辑:家伙感谢您的答案,但我忘了补充一点,每一个元素出现的次数应该是两个列表相同
Guys thanks for the answers but I forgot to add something, the number of occurrences of each element should be the same on both lists.
推荐答案
如果你想他们是真正平等的(即相同的项目和相同数量的每一个项目的),我认为最简单的办法是比较之前排序
If you want them to be really equal (i.e. the same items and the same number of each item), I think that the simplest solution is to sort before comparing:
Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))
编辑:
下面是执行好一点(大约快十倍)的解决方案,并且只需要 IEquatable
,而不是 IComparable的
:
public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2) {
var cnt = new Dictionary<T, int>();
foreach (T s in list1) {
if (cnt.ContainsKey(s)) {
cnt[s]++;
} else {
cnt.Add(s, 1);
}
}
foreach (T s in list2) {
if (cnt.ContainsKey(s)) {
cnt[s]--;
} else {
return false;
}
}
return cnt.Values.All(c => c == 0);
}
编辑2:
要处理的键(例如可空类型弗兰克Tzanabetis指出的)任何数据类型,你可以做一个版本,需要的comparer :
public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) {
var cnt = new Dictionary<T, int>(comparer);
...
这篇关于比较两个List&LT; T&GT;平等的对象,无视秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!