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
相关推荐
谷哥的小弟1 天前
Kali安装图文详解教程
网络安全·教程·kali
zhangfeng11331 天前
Biohub 开源蛋白「世界模型」:ESM 四代界面设计的计算侧上手
教程·开源模型·esm·蛋白设计·biohub
程序员大阳3 天前
副队长 Vue3 教程(17)--组件基础与复用思路
vue3·教程·组件·复用
程序员大阳4 天前
副队长Vue3教程(12)--计算属性 computed
vue3·computed·计算属性·示例·可读·可写
blanks20207 天前
c 语言基础 二级指针理解
c
Maynor9968 天前
Trymodel 使用介绍:一个平台同时用 Claude、GPT、Gemini 和 Grok
人工智能·gpt·ai·程序员·教程·claude·语音
2601_967979129 天前
简单学Python——NumPy库6——数值计算1——累加和累乘
数值计算·numpy·数组·累加·累乘
人生!?10 天前
Linux 从入门到进阶 | 基础语法
linux·笔记·教程
2601_9679791214 天前
纯手写:Python安装pip完整教程,搞了几小时,终于成功
python·教程·pip·安装·包管理
2601_9679873714 天前
Sqlite参考手册
数据库·python·sqlite·api·教程