阅读量:2
在C#中,SortedDictionary是一个有序的键值对集合,它会根据键的自然顺序或者提供的比较器进行排序。要查找SortedDictionary中的元素,可以使用以下方法:
- 使用
ContainsKey(TKey key)方法检查SortedDictionary中是否存在指定的键。如果存在,该方法返回true,否则返回false。
SortedDictionary<int, string> mySortedDictionary = new SortedDictionary<int, string>();
mySortedDictionary.Add(3, "three");
mySortedDictionary.Add(1, "one");
mySortedDictionary.Add(2, "two");
if (mySortedDictionary.ContainsKey(2))
{
Console.WriteLine("Key 2 exists in the SortedDictionary.");
}
else
{
Console.WriteLine("Key 2 does not exist in the SortedDictionary.");
}
- 使用
TryGetValue(TKey key)方法尝试获取SortedDictionary中具有指定键的值。如果找到该键,该方法将返回true并将值存储在out参数中;否则,返回false并将out参数设置为默认值。
SortedDictionary<int, string> mySortedDictionary = new SortedDictionary<int, string>();
mySortedDictionary.Add(3, "three");
mySortedDictionary.Add(1, "one");
mySortedDictionary.Add(2, "two");
string value;
if (mySortedDictionary.TryGetValue(2, out value))
{
Console.WriteLine("Value for key 2 is: " + value);
}
else
{
Console.WriteLine("Key 2 does not exist in the SortedDictionary.");
}
- 使用
IndexOfKey(TKey key)方法获取具有指定键的元素的索引。这个方法在SortedDictionary中查找给定键,并返回其索引。如果找不到该键,则返回-1。
SortedDictionary<int, string> mySortedDictionary = new SortedDictionary<int, string>();
mySortedDictionary.Add(3, "three");
mySortedDictionary.Add(1, "one");
mySortedDictionary.Add(2, "two");
int index = mySortedDictionary.IndexOfKey(2);
if (index != -1)
{
Console.WriteLine("Key 2 is at index: " + index);
}
else
{
Console.WriteLine("Key 2 does not exist in the SortedDictionary.");
}
请注意,IndexOfKey方法在.NET Core 3.0及更高版本中可用。在早期版本的.NET Framework中,您需要使用Keys属性遍历SortedDictionary以查找特定键。
以上就是关于“c# sorteddictionary如何查找”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm