Index of List C#

List<T>.Item[Int32] Property is used to gets or sets the element at the specified index.

Properties of List:

  • It is different from the arrays. A list can be resized dynamically but arrays cannot.
  • List class can accept null as a valid value for reference types and it also allows duplicate elements.
  • If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.

Syntax:

public T this[int index] { get; set; }

Parameter:

index: It is the zero-based index of the element to get or set of type System.Int32.

Return Value: This property returns the element at the specified index.

Exception: This method will give ArgumentOutOfRangeException if the index is less than 0 or index is equal to or greater than Count.

Below are the examples to illustrate the use of List<T>.Item[Int32] Property:

Example 1:

using System;

using System.Collections.Generic;

class Geeks {

    public static void Main(String[] args)

    {

        List<String> firstlist = new List<String>();

        firstlist.Add("A");

        firstlist.Add("B");

        firstlist.Add("C");

        firstlist.Add("D");

        firstlist.Add("E");

        firstlist.Add("F");

        Console.WriteLine("Element at index 2: " + firstlist[2]);

    }

}

Output:

Element at index 2: C

Example 2:

using System;

using System.Collections.Generic;

class Geeks {

    public static void Main(String[] args)

    {

        List<String> firstlist = new List<String>();

        firstlist.Add("A");

        firstlist.Add("B");

        firstlist.Add("C");

        firstlist.Add("D");

        firstlist.Add("E");

        firstlist.Add("F");

        Console.WriteLine("Element at index 2: " + firstlist[2]);

        firstlist[2] = "Z";

        Console.WriteLine("After Setting the new value at 2: " + firstlist[2]);

    }

}

Output:

Element at index 2: C After Setting the new value at 2: Z

Reference:

This post will discuss how to find the index of an element in a list in C#.

The solution should either return the index of the first occurrence of the required element or -1 if it is not present in the list.

1. Using List<T>.IndexOf() method

The recommended solution is to use the List<T>.IndexOf() method, which returns the index of the first occurrence of the specified element in this list, or -1 if there is no such element.

using System.Collections.Generic;

    public static void Main()

        List<int> list = new List<int>() {3, 5, 2, 7, 6};

        int index = list.IndexOf(item);

            Console.WriteLine(String.Format("Element {0} is found at index {1}", item, index));

            Console.WriteLine("Element not found in the given list.");

    Output: Element 5 is found at index 1

Download  Run Code

2. Using List<T>.FindIndex() method

The recommended solution is to use the List<T>.FindIndex() method that returns the index of the first occurrence of the specified element that matches the conditions defined by a specified predicate. This method returns -1 if an item that matches the conditions is not found.

using System.Collections.Generic;

    public static void Main()

        List<int> list = new List<int>() {3, 5, 2, 7, 6};

        int index = list.FindIndex(a => a == item);

            Console.WriteLine(String.Format("Element {0} is found at index {1}", item, index));

            Console.WriteLine("Element not found in the given list.");

    Output: Element 5 is found at index 1

Download  Run Code

3. Using Enumerable.Select() method (System.Linq)

The following code example demonstrates how we can use Enumerable.Select to project over a sequence of values and use both value and each element’s index to find the index of the first occurrence of the specified element in this list.

using System.Collections.Generic;

    public static void Main()

        List<int> list = new List<int>() {3, 5, 2, 7, 6};

            int index = list.Select((elem, index) => new {elem, index})

                        .First(p => p.elem == item)

            Console.WriteLine(String.Format("Element {0} is found at index {1}", item, index));

        catch (InvalidOperationException) {

            Console.WriteLine("Element not found in the given list.");

    Output: Element 5 is found at index 1

Download  Run Code

 
We can avoid try-catch block by using FirstOrDefault() method instead of First():

using System.Collections.Generic;

    public static void Main()

        List<int> list = new List<int>() {3, 5, 2, 7, 6};

        int index = list.Select((element, index) => new {element, index})

                        .FirstOrDefault(x => x.element.Equals(item)) ?. index ?? -1;

            Console.WriteLine(String.Format("Element {0} is found at index {1}", item, index));

            Console.WriteLine("Element not found in the given list.");

    Output: Element 5 is found at index 1

Download  Run Code

4. Performing Linear Search

A naive solution is to perform a linear search on the given list to determine whether the target element is present in the list.

using System.Collections.Generic;

public static class Extensions

    public static int FindIndex<T>(this List<T> list, T item)

        EqualityComparer<T> comparer = EqualityComparer<T>.Default;

        for (int i = 0; i < list.Count; i++)

            if (comparer.Equals(list[i], item)) {

    public static void Main()

        List<int> list = new List<int>() {3, 5, 2, 7, 6};

        int index = list.FindIndex(item);

            Console.WriteLine(String.Format("Element {0} is found at index {1}", item, index));

            Console.WriteLine("Element not found in the given list.");

    Output: Element 5 is found at index 1

Download  Run Code

That’s all about finding the index of an element in a List in C#.


Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂


Video liên quan

Chủ đề