📜  C#| Array.LastIndexOf<T> (T [],T)方法(1)

📅  最后修改于: 2023-12-03 15:14:27.604000             🧑  作者: Mango

C# | Array.LastIndexOf<T> Method

Introduction

The Array.LastIndexOf<T>(T[], T) method is a built-in method in C# that returns the index of the last occurrence of a specified value in an array. The method searches the given array from the end to the beginning and when it finds the first occurrence of the specified value, it returns the index of that occurrence.

This method is very useful when you need to find the index of the last occurrence of a specific element in an array.

Syntax

The syntax of the Array.LastIndexOf<T>(T[], T) method is as follows:

public static int LastIndexOf<T> (T[] array, T value);

The parameters of this method are:

  • array: The one-dimensional, zero-based array to search.
  • value: The value to locate in array.

The return type of the method is an int. The return value is the index of the last occurrence of value in array, if found; otherwise, it returns -1.

Example

Here is a simple example that demonstrates the usage of the Array.LastIndexOf<T>(T[], T) method:

int[] numbers = { 1, 2, 3, 2, 4, 5, 2, 6, 7 };
int indexOfLastTwo = Array.LastIndexOf(numbers, 2);
Console.WriteLine(indexOfLastTwo); // Output: 6

In this example, we have defined an array numbers that contains a few elements. We are searching for the last occurrence of the value 2 in the array using the Array.LastIndexOf<T>(T[], T) method. The method returns the index of the last occurrence of 2 in the array, which is 6, and we print it to the console.

Conclusion

The Array.LastIndexOf<T>(T[], T) method is a very efficient way to search an array from the end to find the last occurrence of a specific value. It returns the index of the last occurrence of the value, which can be very useful in certain programming scenarios.