首页 > 解决方案 > 比较大列表

问题描述

我有两个非常大的列表,每个列表有几十万个项目,一个是完整的,另一个是缺少项目。我需要知道不完整列表中缺少哪些项目。我已经尝试过使用Enumerable.Except,但需要很长时间才能完全比较它们。

标签: c#

解决方案


根据您提供的信息,我认为您应该能够通过在比较之前将字符串转换为整数类型来获得良好的性能优势。

我已经编写了实现的 LINQ 和非 LINQ 版本。主要区别在于.ToDictionary,由于重新分配了更大的内存插槽,调用会稍微慢一些。在非LINQ版本中我们可以使用a HashSet,但是我使用的版本( 4.6.1)不允许我通过指定容量来构造。

// Sample String POS0001:615155172
static long GetKey(string s) => long.Parse("1" + s.Substring(3, 4) + s.Substring(8));
static IEnumerable<string> FindMissing(IEnumerable<string> masterList, ICollection<string> missingList) {
    var missingSet = new Dictionary<long, bool>(missingList.Count);
    foreach (string s in missingList)
        missingSet.Add(GetKey(s), true);

    // Compact LINQ Way, but potentially, ineffecient
    //var missingSet = missingList.ToDictionary(GetKey, s => true);

    return masterList.Where(s => !missingSet.ContainsKey(GetKey(s)));
}

由于您的数据已经排序,因此有更多涉及的单程方法来解决您的问题。让我知道这是否适合您,因为我没有测试台来测试它。


推荐阅读