Reputation: 53
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
Upvotes: 2
Views: 5998
Reputation: 124696
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)
{
...
}
Upvotes: 4