C# 数组 - FindIndex() 方法

C# 教程C# 教程

C# 数组 - FindIndex() 方法更新于 2025/6/8 17:22:17

C# 数组 FindIndex() 方法在找到与指定谓词定义的位置匹配的元素后,返回数组或其部分中首次出现的索引。

语法

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

just-code 复制代码
public static T? FindIndex (T[] array, Predicate match);
public static T? FindIndex (T[], Int32, Predicate match);

参数

此方法接受以下参数 -

返回值

如果找到与谓词匹配的索引,则此方法返回该索引;否则返回 -1。

示例 1:查找第一个偶数的索引

这是 FindIndex() 方法的基本示例,用于显示数组中偶数首次出现的索引 -

demo-code 复制代码
using System;
class Program {
   static void Main() {
      int[] Number = new int[] {1, 2, 3, 4, 5};
   
      // 查找第一个偶数的索引
      int evenN = Array.FindIndex(Number, num => num % 2 == 0);
   
      Console.WriteLine("Index of First Even number is: " + evenN);
   }
}

输出

以下是输出 -

notranslate 复制代码
Index of First Even number is: 1

示例 2:查找字符串的第一个索引

让我们创建一个示例,使用 FindIndex() 方法显示第一个以"c"开头的字符串的索引 -

demo-code 复制代码
using System;
class Program {
   static void Main() {
      string[] names = { "Dipak", "Rhaul", "Chhavi", "Charlie" };
      // 查找以"C"开头的索引名称
      int index_number = Array.FindIndex(names, name => name.StartsWith("C"));
      Console.WriteLine("Index of First name starting with 'C': " + index_number);
   }
}

输出

以下是输出 -

notranslate 复制代码
Index of First name starting with 'C': 2

示例 3:如果未找到匹配项会怎样

让我们看一下 FindIndex() 方法的另一个示例,以及它如何处理在数组中未找到索引的情况 -

demo-code 复制代码
using System;
class Program {
   static void Main() {
      int[] numbers = {1, 3, 5, 7};
      int index = Array.FindIndex(numbers, num => num % 2 == 0);
      Console.WriteLine("Index of first even number: " + index);
   }
}

输出

以下是输出 -

notranslate 复制代码
Index of first even number: -1

示例 4:查找符合条件的自定义对象的索引

在此示例中,我们创建一个自定义对象,该对象包含人员的姓名和年龄。我们使用 FindIndex() 函数显示第一个年龄大于 23 岁的人员的索引 -

demo-code 复制代码
using System;
class Person {
   public string Name {
      get;
      set;
   }
   public int Age {
      get;
      set;
   }
}
class Program {
   static void Main() {
      Person[] people = {
         new Person {
            Name = "Dipak", Age = 25
         },
         new Person {
            Name = "Karan", Age = 30
         },
         new Person {
            Name = "Pankaj", Age = 22
         }
      };
      // 查找第一个年龄大于 23 岁的人的索引
      int first_index = Array.FindIndex(people, person => person.Age > 23);
      Console.WriteLine("Index of First person older than 23: " + first_index);
   }
}

输出

以下是输出 -

notranslate 复制代码
Index of First person older than 23: 0
相关推荐
Logic10119 小时前
C语言/数据结构位运算题解:异或XOR找出被挑选一次的果子编号——只出现一次的数字
c语言·数据结构·算法·数组·位运算·时间复杂度·空间复杂度
从小白到软工1 天前
3-8 用draw.io来绘制界面*
c
从小白到软工1 天前
3-7 项目-图形版井字棋(下)
c
C++ 老炮儿的技术栈2 天前
char 造成的数据溢出
linux·服务器·c语言·c++·算法·c
从小白到软工3 天前
3-5 画矩形和按钮
c
从小白到软工3 天前
3-6 项目-图形版井字棋(上)
c
书生执笔画浮沉3 天前
Linux 内核模块为什么不能自己解决兼容性问题?
linux·c·kernel·update·灵感
Logic1013 天前
C语言/数据结构位运算题解:异或XOR找出数轴移动中只出现一次的指令——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Logic1013 天前
C语言/数据结构贡献法题解:数组权值——所有连续子数组中不同数字个数之和(O(n)解法)
c语言·数据结构·算法·数组·时间复杂度·贡献法·哈希记录