2017-05-30 36 views
1

我有两个List<T>对象。它充满了我自己类iFile的对象,其中包含文件路径和最后一次调用程序的最后编辑日期。
现在我想比较这两个列表,但我当前的代码运行得太慢了! (4分钟为70.000〜条目)C# - 比较两个列表<T>对象如果keypairs相等

这里是我的代码:

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

什么你会建议改变以获得更好的性能?

+0

是什么'files'在这种情况下? –

+0

您可以将iFile对象转换为字典,并将路径作为键。然后你可以在字典上查找应该是O(1) –

回答

0

您可以通过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(); 
+1

感谢您的帮助!工作很好,只花了2秒..我印象深刻! – Tobi