C# List .IndexOf()方法使用示例
C#List<T>.IndexOf()方法
List<T>.IndexOf()方法用于获取列表中元素首次出现的索引。
语法:
int List<T>.IndexOf(T item);
int List<T>.IndexOf(T item, int start_index);
int List<T>.IndexOf(T item, int start_index, int count);参数:
item是类型T的元素,如果找到item,则将返回其第一个匹配项。
start_index是您要在列表中找到元素的起始位置。
count是从“start_index”开始搜索的元素总数。
返回值:它返回 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.IndexOf(20) //输出1
a.IndexOf(100) //输出:-1
a.IndexOf(20, 1) //输出1
a.IndexOf(100, 1) //输出:-1
a.IndexOf(20, 1, 3) //输出1
a.IndexOf(20, 0, 1) //输出:-1C#示例使用List<T>.IndexOf()方法获取列表中元素的索引
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.IndexOf(Titem)
//发现20
int index = a.IndexOf(20);
if (index != -1)
Console.WriteLine("20 found at " + index + " position.");
else
Console.WriteLine("20 does not found in the list");
//找到100
index = a.IndexOf(100);
if (index != -1)
Console.WriteLine("100 found at " + index + " position.");
else
Console.WriteLine("100 does not found in the list");
//使用List.IndexOf(Titem,intindex)
//发现20
index = a.IndexOf(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.IndexOf(100, 1); //起始索引为1
if (index != -1)
Console.WriteLine("100 found at " + index + " position.");
else
Console.WriteLine("100 does not found in the list");
//使用List.IndexOf(Titem,intstart_index,intcount)
//发现20
//搜索将从索引1到接下来的3个元素执行
index = a.IndexOf(20, 1, 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.IndexOf(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 1 position. 100 does not found in the list 20 found at 1 position. 100 does not found in the list 20 found at 1 position. 20 does not found in the list
参考:List<T>.IndexOf方法