在一个列表中查找整数的索引

40

有没有一种方法可以从列表中获取int的索引?寻找像list1.FindIndex(5)这样的东西,其中我想找到列表中5的位置。


list1的类型是什么? - Geoff Cox
5个回答

66
使用列表的 .IndexOf() 方法。该方法的规范可以在 MSDN 上找到。

56

FindIndex 看起来是你要找的函数:

FindIndex(Predicate<T>)

用法:

list1.FindIndex(x => x==5);

例子:

// given list1 {3, 4, 6, 5, 7, 8}
list1.FindIndex(x => x==5);  // should return 3, as list1[3] == 5;

1
对于基本类型,没有必要通过FindIndex谓词重新定义相等性。只有在未定义相等运算符或搜索的比较逻辑与相等性不同时,才应使用此方法。 - Dan Bechard
1
返回第一个匹配项的索引,如果未找到则返回-1。 - Curtis Yallop

6
List<string> accountList = new List<string> {"123872", "987653" , "7625019", "028401"};

int i = accountList.FindIndex(x => x.StartsWith("762"));
//This will give you index of 7625019 in list that is 2. value of i will become 2.
//delegate(string ac)
//{
//    return ac.StartsWith(a.AccountNumber);
//}
//);

5

0

如果你考虑到C#中的泛型列表是从0开始索引的,那么这将变得更加容易,就像一个数组一样。这意味着你可以直接使用以下代码:

int index = 0; int i = accounts[index];


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接