Accepted answer

well you could start from the list instead of the dictionary:

var selectedvalues = keystoselect.where(dictionary1.containskey)
                     .select(x => dictionary1[x])

if all the keys are guaranteed to be in the dictionary you can leave out the first where:

var selectedvalues = => 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.


the accepted solution is still not the most efficient option from the point of lookups as you still have to check if the key is in the dictionary twice: once to filter the keys, once to lookup the object.

this solution does not have that issue:

var selectedvalues = keystoselect
  .select(_ => {
     var found = dict.trygetvalue(_, out tvalue? result);
     return (found, result);
  .where(_ => _.found)
  .select(_ => _.result!)


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 = => dictionary1[k]).tolist();


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)


 var selectvalues = (from keyvaluepair in dictionary1
                     where keystoselect.contains(keyvaluepair.key)
                     select keyvaluepair.value).tolist()

Related Query

More Query from same tag