gpt4 book ai didi

c# - 查找两个列表之间的差异数

转载 作者:行者123 更新时间:2023-11-30 21:15:25 25 4
gpt4 key购买 nike

我想比较两个元素个数相同的列表,找出它们之间的差异个数。现在,我有这段代码(有效):

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com