I need to select a number of values (into a List) from a Dictionary based on a subset of keys.
I\'m trying to do this in a single line of code using Linq but what I have
Well you could start from the list instead of the dictionary:
var selectedValues = keysToSelect.Where(dictionary1.ContainsKey)
.Select(x => dictionary1[x])
.ToList();
If all the keys are guaranteed to be in the dictionary you can leave out the first Where
:
var selectedValues = keysToSelect.Select(x => dictionary1[x]).ToList();
Note this solution is faster than iterating the dictionary, especially if the list of keys to select is small compared to the size of the dictionary, because Dictionary.ContainsKey
is much faster than List.Contains
.