Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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)?

like image 569
Sonny Boy Avatar asked Jul 15 '10 21:07

Sonny Boy


1 Answers

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.

like image 181
LBushkin Avatar answered Sep 20 '22 07:09

LBushkin