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
If you know that all the value that you want to select are in the dictionary, you can loop through the keys instead of looping through the dictionary:
List<ValueType> selectedValues = keysToSelect.Select(k => dictionary1[k]).ToList();
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
.
A Dictionary<TKey,TValue>
is IEnumerable<KeyValuePair<TKey,TValue>>
, so you can simply Select
the Value
property:
List<ValueType> selectedValues = dictionary1
.Where(x => keysToSelect.Contains(x.Key))
.Select(x => x.Value)
.ToList();
or
var selectValues = (from keyValuePair in dictionary1
where keysToSelect.Contains(keyValuePair.Key)
select keyValuePair.Value).ToList()