Find Index of Item in a Chash List in One Step



To get the index of an item in a single line, use the FindIndex() and Contains() methods.

int index = myList.FindIndex(a => a.Contains("Tennis"));

Above, we got the index of an element using the FindIndex(), which is assisted by Contains() method for that specific element.

Here is the complete code ?

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      List < string > myList = new List < string > () {
         "Football",
         "Soccer",
         "Tennis",
      };

      // finding index
      int index = myList.FindIndex(a => a.Contains("Tennis"));

      // displaying index
      Console.WriteLine("List Item Tennis Found at index: " + index);
   }
}

Output

List Item Tennis Found at index: 2
Updated on: 2023-09-09T23:28:21+05:30

40K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements