是否有LINQ方法可以找出两个通用词典之间的区别? 与this question相同,但使用通用词典。
答案 0 :(得分:24)
var diff = dicOne.Except(dicTwo).Concat(dicTwo.Except(dicOne));
答案 1 :(得分:2)
如果性能很重要,您可能希望使用Dictionary类的哈希查找并获得速度提升。我采用了一个包含100万个条目的字典的测试场景,对其进行了深度复制,并对该副本进行了10次编辑(删除了5个条目,添加了5个条目)。 [我有一个任务要做,包括查找数据中的更改,然后仅将更改推送到另一个函数。]
使用LINQ(参见Magnus的回答)根据秒表的时间过去约为3600毫秒。通过使用Dictionary.Contains()进行简单比较,经过的时间约为600毫秒。环境是调试模式下的Visual Studio 2017社区,用于同一台计算机上的ConsoleApp测试工具。
您的里程可能会有所不同,您可能会有适度的行数,因此可能无关紧要,但对于较大的词典,使用Dictionary类的查找功能是值得的。
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;
}
}
}
答案 2 :(得分:0)
这样的事情?
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));