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 found so far seems quite long and clumsy. What would be the shortest (cleanest) way to do this?
This is what I have now (the keys are Strings and keysToSelect is a List of keys to select):
List<ValueType> selectedValues = dictionary1.Where(x => keysToSelect.Contains(x.Key))
.ToDictionary<String, valueType>(x => x.Key,
x => x.Value)
.Values.ToList;
Thank you.
Well you could start from the list instead of the dictionary:
If all the keys are guaranteed to be in the dictionary you can leave out the first
Where: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.ContainsKeyis much faster thanList.Contains.