c# dictionnary根据value查找对应的key

时间:2022-10-04 07:05:38

属性方法中并没有包含此功能,因此需要自己自定义一个方法:

string regionName = "";
if (ControlForm.swichLanguage.Contains("EN"))
{
var regionName1 = en_Resx.Where(q => q.Value == ((Button)sender).Text).Select(q => q.Key);
IEnumerator enumerator = regionName1.GetEnumerator();
while (enumerator.MoveNext())
{
regionName = (string)enumerator.Current;
}
}
else
{
regionName = ((Button)sender).Text;
}

其它方法查看(如下):

 private void GetDicKeyByValue()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("1", "1");
dic.Add("2", "2");
dic.Add("3", "2");
//foreach KeyValuePair traversing
foreach (KeyValuePair<string, string> kvp in dic)
{
if (kvp.Value.Equals("2"))
{
//...... kvp.Key;
}
} //foreach dic.Keys
foreach (string key in dic.Keys)
{
if (dic[key].Equals("2"))
{
//...... key
}
} //Linq
var keys = dic.Where(q => q.Value == "2").Select(q => q.Key); //get all keys List<string> keyList = (from q in dic
where q.Value == "2"
select q.Key).ToList<string>(); //get all keys var firstKey = dic.FirstOrDefault(q => q.Value == "2").Key; //get first key
}