Determine if Dictionary Contains All of a Set of Keys

.net, c#, linq

Solution

Something like this should meet your requirement. Apply proper validations around your arguments, of course.

return keys.Any() 
    && keys.All(key => dictionary.ContainsKey(key));

Note: I include `Any` because `All` will return true if the source sequence (keys) is actually empty. If you don't mind this, then eliminate the use of `Any`.

Problem

I'm trying to figure out the best way to determine if a `Dictionary<string, string>` object contains all of a set of `string` objects as keys. I'm probably not making any sense so here's some example code using a definite set of strings: ``` public static bool ContainsKeys(this Dictionary<string, string> dictionary) { return dictionary.ContainsKey("fname") && dictionary.ContainsKey("lname") && dictionary.ContainsKey("address1") && dictionary.ContainsKey("city") && dictionary.ContainsKey("state") && dictionary.ContainsKey("zip"); } ``` The idea here is to accept an arbitrary set of strings as `keys` and check if the keys of the `Dictionary<string, string>` object contain all of the strings in `keys`. I was trying to go down the LINQ road with this: ``` public static bool ContainsKeys(this Dictionary<string, string> dictionary, string[] keys) { var query = from entry in dictionary where keys.Contains(entry.Key) select entry; return query.Any(); } ``` I have no idea if I'm on the right path though - I think this might work if I wanted to know if `dictionary` contained any of those strings as keys.

Original source