C# 数组 - LastIndexOf() 方法
C# 数组 LastIndexOf() 方法用于在数组中搜索指定的元素或对象,并返回其最后一次出现的索引。当我们想要查找一维数组中某个值的最后一个位置时,此方法非常有用。
一维数组的搜索方式是从最后一个元素开始向后,到第一个元素结束。
异常
此方法有以下异常 -
- ArgumentNullException:当数组为空时。
- RankException:当数组为多维时。
语法
以下是 C# 数组 LastIndexOf() 方法的语法 -
public static int LastIndexOf (Array array, object? value);
此
Array.LastIndexOf(Array, Object, Int32)
此
Array.LastIndexOf(Array, Object, Int32, Int32)
参数
此方法接受以下参数 -
- array:指定要搜索的一维数组。
- object:要在数组中定位的对象。
返回值
如果找到,此方法返回值在数组中最后一次出现的索引;否则,返回数组下限 -1。
示例 1:指定字符串的最后一个索引
这是 LastIndexOf() 方法的基本示例,用于显示指定元素的最后一个索引 -
using System;
class Program {
static void Main() {
string[] fruits = {
"Apple",
"Banana",
"Cherry",
"Banana",
"Grapes"
};
int index = Array.LastIndexOf(fruits, "Banana");
Console.WriteLine($"Last occurrence of 'Banana': {index}");
}
}
输出
以下是输出 -
Last occurrence of 'Banana': 3
示例 2:从指定索引搜索最后一个索引
让我们创建另一个 LastIndexOf() 方法的示例,以显示从最后一个给定位置开始的指定元素的最后一个索引 -
using System;
class Program {
static void Main() {
int[] numbers = { 1, 2, 3, 4, 3, 5, 6 };
int index = Array.LastIndexOf(numbers, 3, 3);
Console.WriteLine($"Index of '3' starting from last position 3: {index}");
}
}
输出
以下是输出 -
Index of '3' starting from last position 3: 2
示例 3:搜索范围内的最后一个索引
让我们看另一个 LastIndexOf() 方法的示例,这里我们指定了范围来搜索该范围内元素的最后一个索引 -
using System;
class Program {
static void Main() {
char[] letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
int index = Array.LastIndexOf(letters, 'f', 7, 4);
Console.WriteLine($"Last Index of 'f': {index}");
}
}
输出
以下是输出 -
Last Index of 'f': 5
示例 4:查找缺失元素
我们来看另一个示例,LastIndexOf() 方法。如果元素或对象不在数组中,LastIndexOf 将显示 -1 -
using System;
class Program {
static void Main() {
double[] values = { 1.1, 2.2, 3.3, 4.4, 5.5 };
int index = Array.LastIndexOf(values, 6.6);
Console.WriteLine($"Last Index of 6.6: {index}");
}
}
输出
以下是输出 -
Last Index of 6.6: -1

csharp_array_class.html