How to select multiple values from a Dictionary using Linq as simple as possible

前端 未结 3 856
-上瘾入骨i
-上瘾入骨i 2021-02-02 07:43

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

相关标签:
3条回答
  • 2021-02-02 08:09

    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();
    
    0 讨论(0)
  • 2021-02-02 08:10

    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.

    0 讨论(0)
  • 2021-02-02 08:25

    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()
    
    0 讨论(0)
提交回复
热议问题