score:46

Accepted answer
 var values = dictionary.where(x => somekeys.contains(x.key)).select(x => x.value);
 var keys = dictionary.where(x => somevalues.contains(x.value)).select(x => x.key);

score:2

the best approach is to perform your linq query on the collection of key-value pairs, then use a select projection to select either the keys or the values at the end of your query. this way there is no need to perform a look-up at the end of your query.

for example:

  dictionary<string, string> data = new dictionary<string, string>();
  // select all values for keys that contain the letter 'a'
  var values = data.where(pair => pair.key.contains("a"))
                   .select(pair => pair.value);

score:11

a dictionary<,> really isn't great for finding keys by value. you could write a bidirectional dictionary, as i have done in this answer, but it wouldn't necessarily be the best approach.

of course you can use a dictionary as a sequence of key/value pairs, so you could have:

var keysforvalues = dictionary.where(pair => values.contains(pair.value))
                              .select(pair => pair.key);

just be aware this will be an o(n) operation, even if your "values" is a hashset or something similar (with an efficient containment check).

edit: if you don't really need a key/value relation - if it's more like they're just pairs - then using list<tuple<foo, bar>> would make a certain amount of sense. the query ends up being the same, basically:

public ienumerable<t1> getallfirst<t1, t2>(ienumerable<tuple<t1, t2>> source,
                                           ienumerable<t2> seconds)
{
    hashset<t2> secondsset = new hashset<t2>(seconds);
    return source.where(pair => secondsset.contains(pair.item2));
}

public ienumerable<t2> getallsecond<t1, t2>(ienumerable<tuple<t1, t2>> source,
                                            ienumerable<t1> firsts)
{
    hashset<t1> firstsset = new hashset<t1>(firsts);
    return source.where(pair => firstsset.contains(pair.item1));
}

Related Query

More Query from same tag