C# 数组 - IndexOf() 方法

C# 数组 IndexOf() 方法在数组中搜索指定对象后,返回该对象在一维数组或元素范围中首次出现的索引。

异常

此方法有以下异常 -

  • ArgumentNullException:当数组为 null 时。
  • RankException:当数组为多维数组时。

语法

以下是 C# 数组 IndexOf() 方法的语法 -

public static int IndexOf (Array array, object? value);

IndexOf() 方法的语法从第一个索引开始搜索指定元素。

Array.IndexOf(Array, Object, Int32)

IndexOf() 方法的语法在数组中指定的元素范围内搜索。

Array.IndexOf(Array, Object, Int32, Int32)

参数

此方法接受以下参数 -

  • array:指定要搜索的一维数组。
  • object:要在数组中定位的对象。

返回值

此方法返回索引如果找到,则返回数组中第一次出现该值的索引;否则,返回数组下限 -1。

示例 1:指定字符串的第一个索引

这是 IndexOf() 方法显示指定元素索引的基本示例 -

using System;

class Program {
   static void Main() {
      string[] fruits = {
         "Apple",
         "Banana",
         "Cherry",
         "Banana",
         "Grapes"
      };
      int index = Array.IndexOf(fruits, "Banana");
      Console.WriteLine($"First occurrence of 'Banana': {index}");
   }
}

输出

以下是输出 -

First occurrence of 'Banana': 1

示例 2:从指定索引处搜索

让我们再创建一个例子,使用 IndexOf() 方法打印从给定索引处开始的指定元素的索引 -

using System;
class Program {
   static void Main() {
      int[] numbers = { 1, 2, 3, 4, 3, 5, 6 };
      int index = Array.IndexOf(numbers, 3, 3);
      Console.WriteLine($"Index of '3' starting from position 3: {index}");
   }
}

输出

以下是输出 -

Index of '3' starting from position 3: 4

示例 3:在一定范围内搜索

我们来看另一个 IndexOf() 方法的示例,这里我们指定了范围,以在该范围内搜索元素的索引 -

using System;

class Program {
   static void Main() {
      char[] letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
      int index = Array.IndexOf(letters, 'f', 2, 4);
      Console.WriteLine($"Index of 'f' within range 2-5: {index}");
   }
}

输出

以下是输出 -

Index of 'f' within range 2-5: 5

示例 4:查找缺失元素

我们来看另一个示例,IndexOf() 方法。如果元素或对象不在数组中,IndexOf 将显示 -1 -

using System;

class Program {
   static void Main() {
      double[] values = { 1.1, 2.2, 3.3, 4.4, 5.5 };
      int index = Array.IndexOf(values, 6.6);
      Console.WriteLine($"Index of 6.6: {index}");
   }
}

输出

以下是输出 -

Index of 6.6: -1

csharp_array_class.html