码迷,mamicode.com
首页 > 其他好文 > 详细

C# Dictionary通过value获取对应的key值

时间:2014-09-28 14:16:02      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

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
}

 

.....

C# Dictionary通过value获取对应的key值

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/vipsoft/p/3998052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!