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)
{
...
}