This post will discuss how to find the index of an element in a list in C#.

The solution should either return the index of the first occurrence of the required element or -1 if it is not present in the list.

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

The recommended solution is to use the List<T>.IndexOf() method, which returns the index of the first occurrence of the specified element in this list, or -1 if there is no such element.

Download  Run Code

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

The recommended solution is to use the List<T>.FindIndex() method that 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.

Download  Run Code

3. Using Enumerable.Select() method (System.Linq)

The following code example demonstrates how we can use Enumerable.Select to project over a sequence of values and use both value and each element’s index to find the index of the first occurrence of the specified element in this list.

Download  Run Code

 
We can avoid try-catch block by using FirstOrDefault() method instead of First():

Download  Run Code

A naive solution is to perform a linear search on the given list to determine whether the target element is present in the list.

Download  Run Code

That’s all about finding the index of an element in a List in C#.