This post will discuss how to find an element in the given list in C#. The solution should return true if the list contains the specified value; otherwise, false.

1. Using Enumerable.Contains() method (System.Linq)

The Enumerable.Contains() method provides a simple, clean way to determine whether a sequence contains a specified element or not. The following example demonstrates the usage of the Contains() method:

Download  Run Code

2. Using List.IndexOf() method

Another good solution is to use the List.IndexOf() method that returns the index of the first occurrence of the specified element in this list and -1 if there is no such element.

Download  Run Code

3. Using List.FindIndex() method

The List.FindIndex() method returns the index of the first element that satisfies the provided predicate. If no element satisfies the condition, FindIndex returns -1.

Download  Run Code

4. Using List.FindAll() method

The List.FindAll() method returns a list containing all the elements that match the specified predicate. We can use it to check the existence of an element in the list, as shown below:

Download  Run Code

5. Using Enumerable.Where() method (System.Linq)

The System.Linq.Enumerable.Where() method filters a sequence of values based on a predicate. The following code example demonstrates how we can use Where() to find the first occurrence of the specified element in this list.

Download  Run Code

 
We can avoid the try-catch block by setting the default value with the DefaultIfEmpty() method:

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 an element in a List in C#.