Dictionary通过Value找到它的key

时间:2024-01-06 21:28:32
 private void GetDicKeyByValue()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("", "");
dic.Add("", "");
dic.Add("", "");
//foreach KeyValuePair traversing
foreach (KeyValuePair<string, string> kvp in dic)
{
if (kvp.Value.Equals(""))
{
//...... kvp.Key;
}
} //foreach dic.Keys
foreach (string key in dic.Keys)
{
if (dic[key].Equals(""))
{
//...... key
}
} //Linq
var keys = dic.Where(q => q.Value == "").Select(q => q.Key); //get all keys List<string> keyList = (from q in dic
where q.Value == ""
select q.Key).ToList<string>(); //get all keys var firstKey = dic.FirstOrDefault(q => q.Value == "").Key; //get first key
}