我想比较两个具有相同元素数量的列表,并找出它们之间的差异数量。现在,我有这个代码(有效):
public static int CountDifferences<T> (this IList<T> list1, IList<T> list2)
{
if (list1.Count != list2.Count)
throw new ArgumentException ("Lists must have the same number of elements", "list2");
int count = 0;
for (int i = 0; i < list1.Count; i++) {
if (!EqualityComparer<T>.Default.Equals (list1[i], list2[i]))
count++;
}
return count;
}
这对我来说感觉很困惑,似乎必须有一种更优雅的方式来实现它。也许有一种方法可以将两个列表组合成一个元组列表,然后简单地检查新列表的每个元素以查看两个元素是否相等?
最佳答案
由于列表中的顺序确实很重要,这就是我的方法:
public static int CountDifferences<T>(this IList<T> list1, IList<T> list2)
{
if (list1.Count != list2.Count)
throw new ArgumentException("Lists must have the same number of elements", "list2");
int count = list1.Zip(list2, (a, b) => a.Equals(b) ? 0 : 1).Sum();
return count;
}
使用Enumerable.Zip()
简单地合并列表然后总结差异,仍然是 O(n),但这只是枚举列表一次。
此外,这种方法适用于同一类型的任何两个 IEnumerable
,因为我们不使用列表索引器(显然除了在防护检查中的计数比较之外)。
关于c# - 查找两个列表之间的差异数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5762312/