2017-05-30 59 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