C# - 如果密钥对相等,则比较两个List <t>对象

时间:2017-05-30 12:55:47

标签: c# performance list compare

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

这是我的代码:

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;
}

您建议您更改哪些内容以获得更好的效果?

1 个答案:

答案 0 :(得分:1)

您可以fPath加入文件。这将在内部使用哈希集来查找两个集合之间的匹配。与具有复杂度O(N)的简单Where搜索不同,哈希集中的搜索具有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();
相关问题