比较两个 List<T>平等的对象,忽略顺序 [英] Compare two List<T> objects for equality, ignoring order
问题描述
另一个列表比较问题.
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.
推荐答案
如果你想让它们真的相等(即相同的item,每个item的数量相同),我认为最简单的解决方案是先排序再比较:
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:
要将任何数据类型作为键处理(例如 Frank Tzanabetis 指出的可为空类型),您可以制作一个采用 比较器 用于字典:
public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) {
var cnt = new Dictionary<T, int>(comparer);
...
这篇关于比较两个 List<T>平等的对象,忽略顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!