首页 > 解决方案 > 比较 2 个字典并返回缺失值

问题描述

我将如何比较这两个字典并仅返回缺少的值?

GetFileListFromBlob ()函数获取所有文件名,我想知道数据库中缺少什么。

还是有更好的方法从这些对象中获取缺失值?我应该使用不同的键/值吗?

Dictionary<int, string> databaseFileList = new Dictionary<int, string>;
Dictionary<int, string> blobFileList = new Dictionary<int, string>;

int counter = 0;
foreach (string f in GetFileListFromDB())
{
    counter++;
    databaseFileList.Add(counter,  f );
}

counter = 0;
foreach (string f in GetFileListFromBlob())
{
    counter++;
    blobFileList.Add(counter, f);
}

// How to compare?

谢谢

标签: c#dictionary.net-core

解决方案


AHashSet<T>可能是您想要的(而不是 a Dictionary<K,V>) - 举个例子:

var reference  = new HashSet<string> {"a", "b", "c", "d"};
var comparison = new HashSet<string> {"a",           "d", "e"};

当您现在调用ExceptWith参考集时...

reference.ExceptWith(comparison);

...reference集合将包含集合"b""c"不存在的元素comparison。但是请注意,"e"不会捕获额外的元素(交换集合以获取"e"缺失的元素)并且该操作会就地修改参考集。如果不希望这样做,则ExceptLINQ 运算符可能值得研究,正如另一个答案中已经提到的那样。


推荐阅读