C#: List

C# List IndexOf


IndexOf searches List collections. It determines the element index of a certain value in the List collection. By using the IndexOf method, you can search for the first position of the value specified.


Method call

First, we use the IndexOf instance method in List. This has two overloads and works the same way as string IndexOf. It accepts the value you want to find as the first parameter. It then returns the location of the value.

C# program that uses IndexOf method on List

using System;
using System.Collections.Generic;

class Program
    static void Main()
	List<int> primes = new List<int>(new int[] { 19, 23, 29 });

	int index = primes.IndexOf(23); // Exists in List

	index = primes.IndexOf(10); // Doesn't exist in List


Cover logo

When using IndexOf, you must always test for -1, or you will get exceptions that you will have to deal with elsewhere. Note that you can also use LastIndexOf to search in the reverse order. It also has overloads.


Note:There is no IndexOfAny method, as the string class has. Using a foreach-loop to test elements is an option.



Framework: NET

The IndexOf method on the List type in the .NET Framework presents a simple and useful way of determining the index of an element value. We looked at an example program of using this method, and discussed its nuances.