[C#] Dictionaryの逆引き

C#のDictionaryでValueからKeyを取得する方法のメモ書きです。

KeyからValueは添字指定で行えますが、逆は一筋縄には行きません。
なぜなら、Dictionary中に同じValueが複数存在している可能性があるためです。
したがって、1つのValueに対してKeyは複数存在する可能性があります。
KeyとValueが一対一の関係が常に成り立っている場合は逆に問題ないでしょう。

以下使用例です。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KeyValue {
    class Program {
        static void Main(string[] args) {
            // 適当なDictionary
            Dictionary<string, int> dic = new Dictionary<string, int>() {
                { "abc", 123 },
                { "def", 456 },
                { "efg", 789 },
            };

            // ValueからKeyを検索
            var key = dic.First(x => x.Value == 123).Key;

            System.Console.WriteLine(key);  // "abc"が出力される
        }
    }
}

Keyを求めるには自力で検索するしかないようです・・・
あまり頻繁に使用することはお勧めできませんが、どうしてもそうせざるを得ない場合はユーティリティ関数にまとめておいたほうが良いと思います。