Dictionary ContainsValue and get key in one step or efficient way to accomplish this task?

StackOverflow https://stackoverflow.com/questions/23557144

  •  18-07-2023
  •  | 
  •  

Question

Is there efficient way to check the value is in the Dictionary once know that value is there and then find the key for that value?

//check dictionary already has sortedWord (i.e key is word and value is sortedWord)

 if (anagramDict.ContainsValue(sortedWord))
     {
       //Get the key for matching the sortedWord 
       string keyWord = anagramDict.Single(kvp => kvp.Value == sortedWord).Key;

Basically reverse request of this question. Dictionary ContainsKey and get value in one function

Was it helpful?

Solution

You ask for "the" key corresponding to a value, but there may be multiple such keys. Therefore you should probably be using .First() rather than .Single().

And a dictionary's sort order is undefined, so looking for the "first" key is ambiguous.

You could do something like the following (also works for keys that are value types):

var keys = dict.Where(kvp => kvp.Value == sortedWord).Select(kvp => kvp.Key).ToList();
if (keys.Count > 0)
{
    // Now you need to decide which matching key you want.
    // If you don't care, you can take the first
    key = keys[0];
}

If you don't care which key you get, it is more efficient to stop at the first match:

var keys = dict.Where(kvp => kvp.Value == sortedWord).Select(kvp => kvp.Key).Take(1).ToList();
if (keys.Count > 0)
{
    key = keys[0];
}

For a dictionary whose keys are a reference type (which is your case: I assume your key is a string), and assuming you don't care which key you get, you can simplify this to:

var key = dict.Where(kvp => kvp.Value == sortedWord).Select(kvp => kvp.Key).FirstOrDefault();
if (key != null)
{
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top