C# 程式用於在陣列中查詢最後一個匹配的元素
要找到最後一個匹配元素,請使用 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 }; // last Index of element 45 int res = Array.LastIndexOf(val, 45); // Display the index Console.WriteLine("Index of element 45 is = "+res); } }
輸出
Index of element 45 is = 5
廣告