简体   繁体   中英

Using LINQ to find all keys from one collection that are not in another?

I'm trying to locate all the keys in one Dictionary that are not in another Dictionary. Obviously, I can do this using a nested loop, but I'm trying to learn LINQ at the moment and I was wondering if I might use it to accomplish this task?

Here's what I have so far:

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

Any idea what should go in place of the question marks (or perhaps instead of the entire where clause)?

You can do:

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

The Except() method is essentially the same as the minus operations in SQL - it returns all items from the first collection excluding those in the second. Since dictionaries expose their keys, you can compute their difference that way.

The Except() operator uses the default equality for the type, but there is also an overload which allows you to specify your own IEqualityComparer to override the semantics of how to compare values. In your example, you probably don't need that - but it's nice to know it there.

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

var missingKeys = dictOne.Keys.Where(x => !dictTwo.ContainsKey(x));
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;

(But LBuskin's answer is much better)

have a look at the Except extension method. HTH.

If you wanted to use query syntax I would do something akin to below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM