Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Dictionary Contains All of a Set of Keys

Tags:

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.

like image 216
Spencer R Avatar asked Feb 20 '13 20:02

Spencer R


3 Answers

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.

like image 178
Anthony Pegram Avatar answered Sep 18 '22 13:09

Anthony Pegram


This can be done pretty simply using the All extension method.

return keys.All(k => dictionary.ContainsKey(k));

This will check that the given predicate (dictionary.ContainsKey(k)) is true for all keys in the given array.

like image 28
yoozer8 Avatar answered Sep 20 '22 13:09

yoozer8


LINQ is indeed good for this sort of thing:

public static bool ContainsKeys(this Dictionary<string, string> dictionary, string[] keys)
{
  return keys.All(dictionary.ContainsKey);
}
like image 45
GraemeF Avatar answered Sep 17 '22 13:09

GraemeF