C# 程序用于查找数组中的最后一个匹配元素

csharpprogrammingserver side programming更新于 2025/9/17 6:15:00

要查找最后一个匹配元素,请使用 Array.LastIndexOf 方法。如果元素不在整数数组中,则返回 -1。

以下是数组 −

int[] val = { 97, 45, 76, 21, 89, 45 };

现在,假设您需要搜索元素 45 的最后一个索引。为此,请使用 Array.LastIndexOf() 方法 −

int res = Array.LastIndexOf(val, 45);

以下是示例 −

示例

using System;
using System.Text;
public class Demo {
   public static void Main() {
      int[] val = { 97, 45, 76, 21, 89, 45 };
      // 元素 45 的最后一个索引
      int res = Array.LastIndexOf(val, 45);
      // 显示索引
      Console.WriteLine("元素 45 的索引 = "+res);
   }
}

输出

元素 45 的索引为 = 5

相关文章