Ok, so you can get a single value by dictionary[key]
or all values by dictionary.Values
.
What I am looking for is a way to get all values for a given key set like so:
List<string> keys;
Dictionary<string, object> dictionary;
List<object> valuesForKeys = GetValuesFromDictionaryUsingKeys(dictionary, keys);
with
private List<object> GetValuesFromDictionaryUsingKeys(Dictionary<string, object> dictionary, List<string> keys)
{
//your code here
}
Of course I could iterate manually over the keylist and use dictionary[key]
each time and add all the values back to a list again, but I would like to use some more elegant way (e.g. Linq).
Thanks.
Try
keys.Where(k => dictionary.ContainsKey(k)).Select(k => dictionary[k])
.Try:
or as requested:
Use .Intersect to remove keys not present in the dictionary, it´s faster than a
.Where(k => dictionary.ContainsKey(k))
.Remove the .Intersect instruction to allow raising an exception for a key not found in the dictionary.
Why write function when you can have generic extension method for everyday use?
EDIT: Than you can write:
Rawling answer works flawlessly, but if you know beforehand the keys exist on the dictionary, this may be more clear and efficient:
keys.Select(k => dictionary[k])