代码之家  ›  专栏  ›  技术社区  ›  Sonny Boy

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

  •  8
  • Sonny Boy  · 技术社区  · 15 年前

    以下是我目前掌握的情况:

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

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

    5 回复  |  直到 13 年前
        1
  •  11
  •   LBushkin    15 年前

    你可以做:

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

    这个 Except() 方法与 minus SQL中的操作—它返回第一个集合中的所有项,不包括第二个集合中的项。因为字典公开了它们的键,所以可以这样计算它们的差异。

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

        2
  •  4
  •   Aren    15 年前
    Dictionary<string, List<string>> dictOne = ...
    Dictionary<string, List<string>> dictTwo = ...
    
    var missingKeys = dictOne.Keys.Where(x => !dictTwo.ContainsKey(x));
    
        3
  •  1
  •   Ian Henry    15 年前
    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;
    

    (但伊布斯金的答案要好得多)

        4
  •  0
  •   andyp    15 年前

    看一看这个 Except 扩展方法。嗯。

        5
  •  0
  •   Kirk    15 年前

    如果您想使用查询语法,我会做类似于以下的操作:

    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)
    {
    }