xxxxxxxxxx
List<int> myList = new List<int> { 10, 20, 30, 40, 50 };
int searchValue = 30;
int index = myList.IndexOf(searchValue);
if (index != -1)
{
Console.WriteLine($"The index of {searchValue} is: {index}");
}
else
{
Console.WriteLine($"{searchValue} was not found in the list.");
}
xxxxxxxxxx
List<string> strings = new List<string>(){"bob","ate","an", "apple"};
strings.IndexOf("bob");
//returns 0
strings.IndexOf("an");
//returns 2
strings.IndexOf("apple");
//returns 3
strings.IndexOf("banana");
//returns -1
//Because banana is not in the list, IndexOf() returns -1
xxxxxxxxxx
// given list1 {3, 4, 6, 5, 7, 8}
list1.FindIndex(x => x==5); // should return 3, as list1[3] == 5;
xxxxxxxxxx
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
int elementToFind = 30;
int index = numbers.IndexOf(elementToFind);
if (index != -1)
{
Console.WriteLine($"The index of {elementToFind} is: {index}");
}
else
{
Console.WriteLine($"{elementToFind} not found in the list.");
}