Collection < T > .IndexOf(T)方法用于搜索指定的对象,并返回整个Collection < T >中第一次出现的从零开始的索引。
句法:
public int IndexOf (T item);
在此, item是要在List < T >中定位的对象。对于引用类型,该值可以为null。
返回值:该方法返回整个Collection
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to search for the specified
// object and returns the zero-based
// index of the first occurrence within
// the entire Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of strings
Collection myColl = new Collection();
// Adding elements in Collection myColl
myColl.Add("A");
myColl.Add("B");
myColl.Add("C");
myColl.Add("D");
myColl.Add("D");
myColl.Add("E");
// Displaying the elements in myColl
foreach(string str in myColl)
{
Console.WriteLine(str);
}
// Searching for the specified object
// and returns the zero-based index of
// the first occurrence within the entire
// Collection. If the object doesn't contain the
// object, then -1 is returned
Console.WriteLine("Index : " + myColl.IndexOf("D"));
}
}
输出:
A
B
C
D
D
E
Index : 3
范例2:
// C# code to search for the specified
// object and returns the zero-based
// index of the first occurrence within
// the entire Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of ints
Collection myColl = new Collection();
// Adding elements in Collection myColl
myColl.Add(2);
myColl.Add(3);
myColl.Add(4);
myColl.Add(5);
// Displaying the elements in myColl
foreach(int i in myColl)
{
Console.WriteLine(i);
}
// Searching for the specified object
// and returns the zero-based index of
// the first occurrence within the entire
// Collection. If the object doesn't contain the
// object, then -1 is returned
Console.WriteLine("Index : " + myColl.IndexOf(7));
}
}
输出:
2
3
4
5
Index : -1
笔记:
- 从第一个元素开始到最后一个元素向前搜索Collection < T>。
- 此方法使用默认的相等比较器EqualityComparer < T >来确定相等。T的默认值T是列表中值的类型。
- 此方法执行线性搜索。因此,此方法是O(n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.indexof?view=netframework-4.7.2