[英]finding difference between two dictionaries
var diff = dicOne.Except(dicTwo).Concat(dicTwo.Except(dicOne));
如果性能很重要,您可能希望使用 Dictionary 類的哈希查找並提高速度。 我采用了一個包含 100 萬個條目的字典的測試場景,對其進行了深度復制,並對副本進行了 10 次編輯(刪除了 5 個條目,添加了 5 個條目)。 [我的任務是查找數據中的更改,然后僅將更改推送到另一個函數。]
使用 LINQ(請參閱 Magnus 的回答),根據秒表,經過的時間約為 3600 毫秒。 通過使用 Dictionary.Contains() 進行簡單比較,經過的時間約為 600 毫秒。 環境是處於調試模式的 Visual Studio 2017 社區,用於 ConsoleApp 測試工具,在同一台機器上。
您的里程可能會有所不同,並且您的行數可能很少,因此這可能無關緊要,但對於較大的字典,使用 Dictionary 類的查找功能是值得的。
在下面的示例中,dicA 和 dicB 是您想要區分的兩個相似的字典對象。 dicAdd 是 A 擁有但 B 中缺少的項目的字典。 dicDel 是相反的,B 包含但 A 沒有的項目。 嘗試使用一些非常簡單的測試詞典,您知道會發生什么,並且應該清楚如何使用。
public static void DiffDictionaries<T, U>(
Dictionary<T, U> dicA,
Dictionary<T, U> dicB,
Dictionary<T, U> dicAdd,
Dictionary<T, U> dicDel)
{
// dicDel has entries that are in A, but not in B,
// ie they were deleted when moving from A to B
diffDicSub<T, U>(dicA, dicB, dicDel);
// dicAdd has entries that are in B, but not in A,
// ie they were added when moving from A to B
diffDicSub<T, U>(dicB, dicA, dicAdd);
}
private static void diffDicSub<T, U>(
Dictionary<T, U> dicA,
Dictionary<T, U> dicB,
Dictionary<T, U> dicAExceptB)
{
// Walk A, and if any of the entries are not
// in B, add them to the result dictionary.
foreach (KeyValuePair<T, U> kvp in dicA)
{
if (!dicB.Contains(kvp))
{
dicAExceptB[kvp.Key] = kvp.Value;
}
}
}
像這樣的東西?
var dicOne = new Dictionary<string, string>(){ {"asdf", "asdf"}, {"few","faew"}};
var dicTwo = new Dictionary<string, string>(){ {"asdf", "asdf"}};
var unContained = dicOne.Where(x => !dicTwo.Contains(x));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.