Find index of an element in a List

In our automation journey we have to deal with multiple types of data, out of them the most common type is list. So here we can get to know how we can get the index of a particular element from a list.

1. Using List<T>.IndexOf() method:-

This returns the index of the first occurrence of the specified element in this list, or -1 if there is no such element.

list = new List(of Int) {3, 5, 2, 7, 6}

Here let say we want to get the index of element 5 so,

item = 5
index = list.IndexOf(item)

Output: Element 5 is found at index 1

2. Using List<T>.FindIndex() method

This returns the index of the first occurrence of the specified element that matches the conditions defined by a specified predicate. This method returns -1 if an item that matches the conditions is not found.

list = new List(of Int)() {3, 5, 2, 7, 6}
item = 5
index = list.FindIndex(Function(x) x.Equals(item))

Output: Element 5 is found at index 1

1 Like