列表<T>。LastIndexOf()方法用于获取列表中元素最后一次出现的索引。
语法:
int List<T>.LastIndexOf(T item); int List<T>.LastIndexOf(T item, int start_index); int List<T>.LastIndexOf(T item, int start_index, int count);
参数:
item是类型T的元素,如果找到item,则将返回其第一个匹配项。
start_index是您要在列表中找到元素的起始位置。
count是从“ start_index”开始搜索的元素总数(向后)。
返回值:它返回指数的元素,如果在指定索引的列表元素创立,如果元素没有在列表中找到-它返回-1。
注意:方法在列表中向后搜索元素。
示例
int list declaration: List<int> a = new List<int>(); adding elements: a.Add(10); a.Add(20); a.Add(30); a.Add(40); a.Add(50); a.Add(10); a.Add(20); a.Add(30); a.Add(40); a.Add(50); Method calls: a.LastIndexOf(20) //输出:6 a.LastIndexOf(100) //输出:-1 a.LastIndexOf(20, 1) //输出1 a.LastIndexOf(100, 1) //输出:-1 a.LastIndexOf(20, 1, 3) //输出:-1 a.LastIndexOf(20, 0, 1) //输出:-1
using System; using System.Text; using System.Collections.Generic; namespace Test { class Program { static void printList(List<int> lst) { //打印元素 foreach (int item in lst) { Console.Write(item + " "); } Console.WriteLine(); } static void Main(string[] args) { //整数列表 List<int> a = new List<int>(); //添加元素 a.Add(10); a.Add(20); a.Add(30); a.Add(40); a.Add(50); a.Add(10); a.Add(20); a.Add(30); a.Add(40); a.Add(50); //打印列表 Console.WriteLine("list elements..."); printList(a); //使用List.LastIndexOf(T item) //发现20 int index = a.LastIndexOf(20); if (index != -1) Console.WriteLine("20 found at " + index + " position."); else Console.WriteLine("20 does not found in the list"); //找到100 index = a.LastIndexOf(100); if (index != -1) Console.WriteLine("100 found at " + index + " position."); else Console.WriteLine("100 does not found in the list"); //使用List.LastIndexOf(T item,int index) //发现20 index = a.LastIndexOf(20, 1); //起始索引为1 if (index != -1) Console.WriteLine("20 found at " + index + " position."); else Console.WriteLine("20 does not found in the list"); //找到100 index = a.LastIndexOf(100, 1); //起始索引为1 if (index != -1) Console.WriteLine("100 found at " + index + " position."); else Console.WriteLine("100 does not found in the list"); //使用List.LastIndexOf(T item,int start_index,int count) //发现20 //搜索将从第9个索引向后3个元素执行 index = a.LastIndexOf(20, 9, 3); if (index != -1) Console.WriteLine("20 found at " + index + " position."); else Console.WriteLine("20 does not found in the list"); //发现20 //搜索将从第0个索引向后1元素执行 index = a.LastIndexOf(20, 0, 1); if (index != -1) Console.WriteLine("20 found at " + index + " position."); else Console.WriteLine("20 does not found in the list"); //按ENTER退出 Console.ReadLine(); } } }
输出结果
list elements... 10 20 30 40 50 10 20 30 40 50 20 found at 6 position. 100 does not found in the list 20 found at 1 position. 100 does not found in the list 20 does not found in the list 20 does not found in the list
参考:List <T> .LastIndexOf方法