使用LINQ从一个集合中查找不在另一个集合中的所有密钥?

时间:2010-07-15 21:07:45

标签: c# .net linq

我正在尝试找到一个字典中不在另一个字典中的所有键。显然,我可以使用嵌套循环来做到这一点,但我现在正在尝试学习LINQ,我想知道我是否可以用它来完成这项任务?

这是我到目前为止所拥有的:

Dictionary<string, List<string>> DBtables = this.CollectTableListings();
var generic = from Dictionary<string,List<string>> tab
              in DBtables
              where !_tables.ContainsKey(???)
              select tab;

知道应该用什么代替问号(或者可能代替整个where子句)?

5 个答案:

答案 0 :(得分:11)

你可以这样做:

var resultKeys = DBTables.Keys.Except( _tables.Keys );

Except()方法与SQL中的minus操作基本相同 - 它返回第一个集合中的所有项目,不包括第二个集合中的项目。由于字典暴露了它们的键,你可以用这种方式计算它们的差异。

Except()运算符使用类型的默认相等,但也有一个重载,允许您指定自己的IEqualityComparer来覆盖如何比较值的语义。在你的例子中,你可能不需要 - 但在那里知道它很好。

答案 1 :(得分:3)

Dictionary<string, List<string>> dictOne = ...
Dictionary<string, List<string>> dictTwo = ...

var missingKeys = dictOne.Keys.Where(x => !dictTwo.ContainsKey(x));

答案 2 :(得分:1)

Dictionary<string, List<string>> dictionary = this.CollectTableListings();
Dictionary<string, List<string>> otherDictionary = getOtherTable();

var keys = from key in dictionary.Keys
           where !otherDictionary.Keys.Contains(key)
           select key;

(但LBuskin的回答要好得多)

答案 3 :(得分:0)

查看Except扩展方法。 HTH。

答案 4 :(得分:0)

如果你想使用查询语法,我会做类似于下面的事情:

var keys = from d1 in dictionary1
           select d1.Key;
var items = from d2 in dictionary2
            where d2.Key in keys
            select d2;
foreach(var item in items)
{
}