C#中dictionary如何根據(jù)索引值獲取Key值
C#dictionary根據(jù)索引值獲取Key值
根據(jù)dictionary索引獲取Key和Value值
var key = dictionary.ElementAt("索引值").Key; var value= dic.ElementAt("索引值").Value;
獲取一個序列的隨機開始時間,并設(shè)置對應(yīng)的結(jié)束時間
Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("06:00", "07:30"); dic.Add("08:00", "11:30"); dic.Add("12:00", "14:00"); dic.Add("14:30", "17:00"); dic.Add("16:00", "21:00"); dic.Add("17:00", "21:00"); dic.Add("19:00", "21:00"); /// <summary> /// 獲取開始和結(jié)束時間 /// </summary> private void GetTime(out DateTime dtStart, out DateTime dtEnd) { var strKey= dic.ElementAt(ran.Next(dic.Count())).Key; var strValue = dic[strKey]; dtStart = DateTime.Parse(strKey); dtEnd = DateTime.Parse(strValue); }
C#字典根據(jù)值查找對應(yīng)的鍵
在C#中,可以使用 LINQ 擴展方法來根據(jù)字典的值查找對應(yīng)的鍵。
可以使用以下代碼:
Dictionary<string, int> dict = new Dictionary<string, int>() { {"apple", 1}, {"banana", 2}, {"orange", 3}, }; string key = dict.FirstOrDefault(x => x.Value == 2).Key; Console.WriteLine(key);
這將輸出 "banana",因為它是值為 2 的鍵。
請注意,此方法只返回字典中找到的第一個匹配項的鍵。如果有多個鍵具有相同的值,則只返回找到的第一個鍵。
如果找不到任何匹配項,則返回默認(rèn)值(在示例中為 null)。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#類型轉(zhuǎn)換之自定義隱式轉(zhuǎn)換和顯式轉(zhuǎn)換
本文主要為大家介紹了一個新的類型轉(zhuǎn)換方法:通過自定義隱式轉(zhuǎn)換,把不一樣的數(shù)據(jù)類型反序列化為一樣的數(shù)據(jù)類型,需要的同學(xué)可以參考一下2022-03-03DevExpress GridControl實現(xiàn)根據(jù)RowIndex和VisibleColumnsIndex來獲取單元格
這篇文章主要介紹了DevExpress GridControl實現(xiàn)根據(jù)RowIndex和VisibleColumnsIndex來獲取單元格值,需要的朋友可以參考下2014-08-08