找到两个词典之间的差异

是否有LINQ方法来查找两个通用字典之间的区别?
与此问题相同,但使用通用词典。

 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类的查找function是值得的。

  public static void DiffDictionaries( Dictionary dicA, Dictionary dicB, Dictionary dicAdd, Dictionary dicDel) { // dicDel has entries that are in A, but not in B, // ie they were deleted when moving from A to B diffDicSub(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(dicB, dicA, dicAdd); } private static void diffDicSub( Dictionary dicA, Dictionary dicB, Dictionary dicAExceptB) { // Walk A, and if any of the entries are not // in B, add them to the result dictionary. foreach (KeyValuePair kvp in dicA) { if (!dicB.Contains(kvp)) { dicAExceptB[kvp.Key] = kvp.Value; } } } 

这样的事情?

 var dicOne = new Dictionary(){ {"asdf", "asdf"}, {"few","faew"}}; var dicTwo = new Dictionary(){ {"asdf", "asdf"}}; var unContained = dicOne.Where(x => !dicTwo.Contains(x));