List<T>.Contains() / IndexOf()
The Contains() method checks whether a list contains a specified element, and IndexOf() returns the index of the first occurrence of an element.
Syntax
using System.Collections.Generic; // Returns true if the specified element exists in the list. list.Contains(T item) // Returns the index of the first occurrence of the specified element. Returns -1 if not found. list.IndexOf(T item) // Starts searching from startIndex. list.IndexOf(T item, int startIndex) // Returns the index of the last occurrence of the specified element. list.LastIndexOf(T item)
Method List
| Method | Description |
|---|---|
| Contains(T item) | Returns true if the list contains item. Searches sequentially, so the time complexity is O(n). |
| IndexOf(T item) | Returns the index of the first occurrence of item. Returns -1 if not found. |
| IndexOf(T item, int startIndex) | Starts searching from startIndex and returns the index of the first matching element. |
| LastIndexOf(T item) | Returns the index of the last occurrence of item. Returns -1 if not found. |
Sample Code
using System;
using System.Collections.Generic;
List<string> languages = new List<string> { "C#", "Java", "Python", "Java", "Go" };
// Check for existence using Contains().
Console.WriteLine(languages.Contains("Python")); // True
Console.WriteLine(languages.Contains("Swift")); // False
// A typical pattern for using Contains() with an if statement.
if (languages.Contains("C#"))
{
Console.WriteLine("C# is in the list.");
}
// Get the index of the first occurrence using IndexOf().
Console.WriteLine(languages.IndexOf("Java")); // 1
Console.WriteLine(languages.IndexOf("Swift")); // -1 (not found, so -1)
// Get the index of the last occurrence using LastIndexOf().
Console.WriteLine(languages.LastIndexOf("Java")); // 3
// Check for duplicates using IndexOf() and LastIndexOf().
int first = languages.IndexOf("Java");
int last = languages.LastIndexOf("Java");
if (first != last)
{
Console.WriteLine("Java appears more than once.");
}
Notes
Both Contains() and IndexOf() scan the list from the beginning, so they take time proportional to the number of elements (O(n)). If you need frequent lookups, consider using Dictionary<TKey, TValue> or HashSet<T> instead. These support O(1) lookups.
For sorting and iterating over a list, see List<T>.Sort() / Reverse() / ForEach().
If you find any errors or copyright issues, please contact us.