C# Dictionary已知value获取对应的key

1:循环遍历法,分为遍历key-value键值对和遍历所有key两种形式

2:使用Linq查询法

     private void GetDictKeyByValue()
{
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(, "");
dict.Add(, "");
dict.Add(, "");
dict.Add(, ""); // foreach KeyValuePair
List<int> list = new List<int>();
foreach (KeyValuePair<int, string> kvp in dict)
{
if (kvp.Value.Equals(""))
{
list.Add(kvp.Key); // kvp.Key;
}
} // foreach dic.Keys
list.Clear();
foreach (int key in dict.Keys)
{
if (dict[key].Equals(""))
{
list.Add(key); // key
}
} // Linq
List<int> keyList = dict.Where(q => q.Value == "")
.Select(q => q.Key).ToList<int>(); //get all keys keyList = (from q in dict
where q.Value == ""
select q.Key).ToList<int>(); //get all keys var firstKey = dict.FirstOrDefault(q => q.Value == "").Key; //get first key
}
上一篇:Oracle变量的定义、赋值及使用


下一篇:织梦CMS增加复制文档功能