C#中dictionary如何根据索引值获取Key值
作者:风,停下
这篇文章主要介绍了C#中dictionary如何根据索引值获取Key值问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
C#dictionary根据索引值获取Key值
根据dictionary索引获取Key和Value值
var key = dictionary.ElementAt("索引值").Key; var value= dic.ElementAt("索引值").Value;
获取一个序列的随机开始时间,并设置对应的结束时间
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> /// 获取开始和结束时间 /// </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#字典根据值查找对应的键
在C#中,可以使用 LINQ 扩展方法来根据字典的值查找对应的键。
可以使用以下代码:
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 的键。
请注意,此方法只返回字典中找到的第一个匹配项的键。如果有多个键具有相同的值,则只返回找到的第一个键。
如果找不到任何匹配项,则返回默认值(在示例中为 null)。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。