SortedList.IndexOfKey(Object)方法用于获取SortedList对象中指定键的从零开始的索引。
句法:
public virtual int IndexOfKey (object key);
在此, key是要位于SortedList对象中的Key。
返回值:如果在SortedList对象中找到了键,则System.Int32
类型的从零开始的索引,否则返回-1。
例外情况:
- ArgumentNullException :如果键为null。
- InvalidOperationException :如果比较器引发异常。
下面的程序说明了上面讨论的方法的使用:
范例1:
// C# code to get the zero-based index
// of the specified key in a SortedList
// object
using System;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// Creating a SortedList of integers
SortedList mylist = new SortedList();
// Adding elements to SortedList
mylist.Add("First", "Ram");
mylist.Add("Second", "Shyam");
mylist.Add("Third", "Mohit");
mylist.Add("Fourth", "Rohit");
mylist.Add("Fifth", "Manish");
// printing the keys and values of mylist
Console.WriteLine("Index \t\t Keys \t\tValues");
for (int i = 0; i < mylist.Count; i++)
{
Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i,
mylist.GetKey(i), mylist.GetByIndex(i));
}
Console.Write("\nThe index of key 'Third' is: ");
// getting the index of key "Third"
Console.Write(mylist.IndexOfKey("Third"));
// getting the index of key which is
// not present in mylist so it will
// return -1
Console.Write("\nThe index of key 'Sixth' is: ");
Console.Write(mylist.IndexOfKey("Sixth"));
}
}
输出:
Index Keys Values
[0] Fifth Manish
[1] First Ram
[2] Fourth Rohit
[3] Second Shyam
[4] Third Mohit
The index of key 'Third' is: 4
The index of key 'Sixth' is: -1
示例2:演示ArgumentNullException
可能发生的情况
// C# code to get the zero-based index
// of the specified key in a SortedList
// object
using System;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// Creating a SortedList of integers
SortedList mylist = new SortedList();
// Adding elements to SortedList
mylist.Add("1", "C++");
mylist.Add("2", "Java");
mylist.Add("3", "DSA");
mylist.Add("4", "Python");
mylist.Add("5", "C#");
// printing the keys and values of mylist
Console.WriteLine("Index \t\t Keys \t\tValues");
for (int i = 0; i < mylist.Count; i++)
{
Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i,
mylist.GetKey(i), mylist.GetByIndex(i));
}
Console.Write("\nThe index of key 'null' is: ");
// getting the index of key "null"
// it will give ArgumentNullException
Console.Write(mylist.IndexOfKey(null));
}
}
运行时错误:
Unhandled Exception:
System.ArgumentNullException: Key cannot be null.
Parameter name: key
笔记:
- 索引序列基于排序序列。添加元素后,它会以正确的排序顺序插入SortedList中,索引也会相应调整。删除元素后,索引也会相应调整。因此,特定键/值对的索引可能会更改。
- 此方法使用二进制搜索算法,因此,此方法是O(log n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.sortedlist.indexofkey?view=netframework-4.7.2