zoukankan      html  css  js  c++  java
  • 【C#】Dictionary通过value获取对应的key值

    通过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

  • 相关阅读:
    左偏树
    论在Windows下远程连接Ubuntu
    ZOJ 3711 Give Me Your Hand
    SGU 495. Kids and Prizes
    POJ 2151 Check the difficulty of problems
    CodeForces 148D. Bag of mice
    HDU 3631 Shortest Path
    HDU 1869 六度分离
    HDU 2544 最短路
    HDU 3584 Cube
  • 原文地址:https://www.cnblogs.com/xihong2014/p/15047770.html
Copyright © 2011-2022 走看看