
IndexOf searches List collections. You want to determine the element index of a certain value in the List collection in your C# program. By using the IndexOf method, you can search for the first position of the value specified.
This C# example program uses the IndexOf method on the List type.
First, here we see the IndexOf instance method in List, which has two overloads and works the same way as string IndexOf. It accepts the value you want to find as the first parameter, and 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
Description. 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. There is no IndexOfAny method, as the string class has.
String.IndexOf String.LastIndexOf Array.IndexOf Array.LastIndexOf
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.
Collections