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

前端 未结 3 901
-上瘾入骨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: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.

提交回复
热议问题