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

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

    A Dictionary is IEnumerable>, so you can simply Select the Value property:

     List 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()
    

提交回复
热议问题