SortedList.IndexOfValue(Object)方法用于获取SortedList对象中第一次出现的指定值的从零开始的索引。
句法:
public virtual int IndexOfValue (object value);
在此, value是要位于SortedList对象中的Value。该值可以为空。
返回值:该方法返回的值参数的第一个匹配的基于零的索引,如果该值在排序列表对象否则返回-1找到。
下面的程序说明了上面讨论的方法的使用:
范例1:
// C# code to get the zero-based index
// of the first occurrence of the specified
// value 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", "Rohit");
mylist.Add("Third", "Mohit");
//taking value "Rohit" twice
// but it give the first occurrence
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 value 'Rohit' is: ");
// getting the index of value "Rohit"
Console.Write(mylist.IndexOfValue("Rohit"));
// getting the index of value which is
// not present in mylist so it will
// return -1
Console.Write("\nThe index of value 'Kirti' is: ");
Console.Write(mylist.IndexOfValue("Kirti"));
}
}
输出:
Index Keys Values
[0] Fifth Manish
[1] First Ram
[2] Fourth Rohit
[3] Second Shyam
[4] Third Mohit
The index of value 'Rohit' is: 2
The index of value 'Kirti' is: -1
范例2:
// C# code to get the zero-based index
// of the first occurrence of the specified
// value 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");
// taking a value null
mylist.Add("4", null);
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 value 'null' is: ");
// getting the index of value "null"
// it will give ArgumentNullException
Console.Write(mylist.IndexOfValue(null));
}
}
输出:
Index Keys Values
[0] 1 C++
[1] 2 Java
[2] 3 DSA
[3] 4
[4] 5 C#
The index of value 'null' is: 3
笔记:
- 索引序列基于排序序列。添加元素后,它会以正确的排序顺序插入SortedList中,索引也会相应调整。删除元素后,索引也会相应调整。因此,特定键/值对的索引可能会更改。
- 使用Equals方法将SortedList元素的值与指定值进行比较。
- 该方法使用线性搜索。因此,此方法是O(n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.sortedlist.indexofvalue?view=netframework-4.7.2