To get the index we can use int index = myList.FindIndex(a => a.StartsWith("string_to_search"));
when we are sure the string exists in myList
.
But how to check if it is present in the List and get its index if it is present? For the time being, I am using the following code.
int ii=0;
foreach (var item in myList){
if (item == "string_to_search")
Console.WriteLine("Found at index: " + ii);
// index is ii
ii++;
}
Is there any better way to do this ?
Use IndexOf
method to find index of item in list. This method returns -1 in case item does not exist in the list.
var itemIndex = myList.IndexOf("string_to_search")
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments