通過key值獲取value值方法想必大家都知道
private void GetDicValueByKey()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("1", "1");
dic.Add("2", "2");
dic.Add("3", "2");
string value;
dic.TryGetValue("2",out value);//......value
}
1:最直白的循環遍歷方法,可以分為遍歷key--value鍵值對以及所有的key兩種表現形式
2:用Linq的方式去查詢(添加對應的命名空間:using System.Linq)
如下為一個十分簡單的代碼示例:
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
}
————————————————
版權聲明:本文為CSDN博主「即步」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_33747722/article/details/77922890