C# ArrayList - IndexOf() 方法
C# ArrayList IndexOf() 方法用于在 ArrayList 中查找特定元素首次出现的索引。如果在 ArrayList 中未找到该元素,则返回 -1。
语法
以下是 C# ArrayList IndexOf() 方法的语法 -
该方法用于查找给定元素在整个 ArrayList 中首次出现的索引。
public virtual int IndexOf(object value);
从 ArrayList 中的指定索引开始搜索指定元素。
public virtual int IndexOf(object value, int startIndex);
从 startIndex 开始,在指定范围内的元素中搜索指定元素,直到下一个 count 个元素为止。
public virtual int IndexOf(object value, int startIndex, int count);
参数
此方法根据所有重载语法接受以下参数 -
- value:ArrayList 中待搜索的元素。
- startIndex:指定 ArrayList 中的起始索引,搜索将从此处开始。
- count:ArrayList 中待搜索元素的数量。
返回值
此方法返回该值第一次出现的索引值;否则返回 -1。
示例 1:使用 IndexOf(object value)
以下是 IndexOf() 方法的基本示例。在这里,我们使用默认语法从整个 ArrayList 中搜索元素 -
using System; using System.Collections; class Example { static void Main() { // 创建一个 ArrayList ArrayList arrayList = new ArrayList { "A", "B", "C", "D", "B" }; // 查找"B"第一次出现的索引 int index = arrayList.IndexOf("B"); Console.WriteLine($"The first occurrence of 'B' is at index: {index}"); } }
输出
以下是输出 -
The first occurrence of 'B' is at index: 1
示例 2:使用 IndexOf(object value, int startIndex)
我们来看另一个 IndexOf() 方法的示例。这里,我们从给定的 startIndex 开始在 ArrayList 中搜索元素 -
using System; using System.Collections; class Example { static void Main() { // 创建一个 ArrayList ArrayList arrayList = new ArrayList { "B", "A", "B", "C", "D" }; // 查找"B"第一次出现的索引 // 从索引 1 开始 int index = arrayList.IndexOf("B", 1); Console.WriteLine($"The first occurrence of 'B' is at index: {index}"); } }
输出
以下是输出 -
The first occurrence of 'B' is at index: 2
示例 3:使用 IndexOf(object value, int startIndex, int count)
以下是 IndexOf() 方法的另一个版本。这里,我们在 ArrayList 中从给定的起始索引开始,在特定数量的元素中搜索元素 -
using System; using System.Collections; class Program { static void Main() { ArrayList arrayList = new ArrayList { "A", "C", "E", "B", "B" }; // 从索引 1 开始查找"B"的索引, // 查找接下来的 3 个元素 int index = arrayList.IndexOf("B", 1, 3); Console.WriteLine($"The first occurrence of 'B' in the specified range is at index: {index}"); } }
输出
以下是输出 -
The first occurrence of 'B' in the specified range is at index: 3
示例 4:在 Person 类中搜索对象
以下示例使用 IndexOf 方法在 ArrayList 中搜索可用的 Person 对象。如果存在,则该方法返回其索引 -
using System; using System.Collections; class Example { public string Name { get; set; } public int Age { get; set; } // 覆盖 Equals 来定义 Person 对象的相等性 public override bool Equals(object obj) { if (obj is Example other) { return this.Name == other.Name && this.Age == other.Age; } return false; } public override int GetHashCode() { return HashCode.Combine(Name, Age); } } class Program { static void Main() { // 创建 Person 对象的 ArrayList ArrayList people = new ArrayList { new Example { Name = "Aman", Age = 25 }, new Example { Name = "Akash", Age = 30 }, new Example { Name = "Rahul", Age = 35 } }; // 创建一个 Person 对象来搜索 Example personToFind = new Example { Name = "Akash", Age = 30 }; int index = people.IndexOf(personToFind); if (index != -1) { Console.WriteLine($"Person found at index: {index}"); } else { Console.WriteLine("Person not found in the list."); } } }
输出
以下是输出 -
Person found at index: 1