【问题标题】:C# - Compare two List<T> Objects if keypairs are equalC# - 如果密钥对相等,则比较两个 List<T> 对象
【发布时间】:2017-05-30 12:55:47
【问题描述】:

我有两个List&lt;T&gt; 对象。它充满了我自己的类 iFile 的对象,其中包含文件路径和程序最后一次调用的最后编辑日期。
现在我想比较这两个列表,但是我当前的代码运行速度太慢了! (约 70.000 个条目需要 4 分钟)

这是我的代码:

private static List<iFile> compareLists(List<iFile> old)
{
    List<iFile> cf = new List<iFile>();
    foreach(iFile file in files)
    {
        bool notChanged = false;

        iFile oldFile = files.Where(f => f.fPath == file.fPath).FirstOrDefault();
        if(oldFile != null & oldFile.lastChange.Equals(file.lastChange))
        {
            notChanged = true;
        }
        if(!notChanged)
        {
            cf.Add(file);
        }
    }
    return cf;
}

您建议进行哪些更改以获得更好的性能结果?

【问题讨论】:

  • 在这种情况下files 是什么?
  • 你可以把你的 iFile 对象变成一个字典 以路径为键。然后你可以在字典上查找应该是 O(1)

标签: c# performance list compare


【解决方案1】:

您可以通过fPath 加入文件。这将在内部使用哈希集来查找两个集合之间的匹配项。与简单的Where 搜索具有 O(N) 复杂度不同,在哈希集中搜索具有 O(1) 复杂度:

var modifiedFiles = from file in files
                    join oldFile in old on file.fPath equals oldFile.fPath
                    where oldFile.lastChange != file.lastChange
                    select file;

return modifiedFiles.ToList();

【讨论】:

  • 感谢您的帮助!工作得很好,只用了 2 秒。我印象深刻!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 1970-01-01
  • 2013-04-18
  • 1970-01-01
  • 2010-12-05
相关资源
最近更新 更多