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

标签 c# linq list comparison

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

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/

相关文章:

javascript - 从 MVC 加载数据 Jtable 时出错?

c# - 动态渐变

C# 将 .csv 文件从本地机器复制到远程 postgresql 服务器

c# - AutoMapper 在投影到可为 null 的枚举时抛出异常

python - 根据列表中的匹配词将单词大写

c# - 如何在不手动设置的情况下将绑定(bind)属性作为参数传递

c# - 如何阅读文本框中的最后一行?

c# - 将数组中的字符串项添加到对象列表

c# - 如何一次性删除通用列表中的所有空元素?

list - Haskell处理Maybe列表