C# 数组 - FindIndex() 方法
C# 数组 FindIndex() 方法在找到与指定谓词定义的位置匹配的元素后,返回数组或其部分中首次出现的索引。
语法
以下是 C# 数组 FindIndex() 方法的语法 -
public static T? FindIndex<T> (T[] array, Predicate<T> match); public static T? FindIndex<T> (T[], Int32, Predicate<T> match);
参数
此方法接受以下参数 -
- array:用于搜索索引的一维零基数组。
- match:定义要搜索元素条件的谓词。
返回值
如果找到与谓词匹配的索引,则此方法返回该索引;否则返回 -1。
示例 1:查找第一个偶数的索引
这是 FindIndex() 方法的基本示例,用于显示数组中偶数首次出现的索引 -
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); } }
输出
以下是输出 -
Index of First Even number is: 1
示例 2:查找字符串的第一个索引
让我们创建一个示例,使用 FindIndex() 方法显示第一个以"c"开头的字符串的索引 -
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); } }
输出
以下是输出 -
Index of First name starting with 'C': 2
示例 3:如果未找到匹配项会怎样
让我们看一下 FindIndex() 方法的另一个示例,以及它如何处理在数组中未找到索引的情况 -
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); } }
输出
以下是输出 -
Index of first even number: -1
示例 4:查找符合条件的自定义对象的索引
在此示例中,我们创建一个自定义对象,该对象包含人员的姓名和年龄。我们使用 FindIndex() 函数显示第一个年龄大于 23 岁的人员的索引 -
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); } }
输出
以下是输出 -
Index of First person older than 23: 0