C# List IndexOf

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.

Example

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 in the array.

Program that uses IndexOf method on List: C#

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
	Console.WriteLine(index);

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

Output

1
-1
Programming tip

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.

String.IndexOfString.LastIndexOfArray.IndexOfArray.LastIndexOfOverload Method

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

Foreach

Summary

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.


C#: Collections: List