find index of an int in a list
Is there a way to get the index of an int from a list?
Looking for something like list1.FindIndex(5)
where I want to find 开发者_运维知识库the position of 5 in the list.
Use the .IndexOf()
method of the list. Specs for the method can be found on MSDN.
FindIndex seems to be what you're looking for:
FindIndex(Predicate<T>)
Usage:
list1.FindIndex(x => x==5);
Example:
// given list1 {3, 4, 6, 5, 7, 8}
list1.FindIndex(x => x==5); // should return 3, as list1[3] == 5;
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);
//}
//);
Try IndexOf.
It's even easier if you consider that the Generic List in C# is indexed from 0 like an array. This means you can just use something like:
int index = 0; int i = accounts[index];
精彩评论