C# Dictionary通過value獲取對應的key值


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
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM