How To Get Last Index Of An Item In A C# List

C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.
 
List is a generic class. You must import the following namespace before using the List<T> class.
  1. using System.Collections.Generic;   
The LastIndexOf method returns the last index of an item if found in the List. 
The following code snippet shows how to use the Contains, the IndexOf and the LastIndexOf methods. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. namespace ConsoleApp1  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             List<string> AuthorList = new List<string>();  
  10.             AuthorList.Add("Mahesh Chand");  
  11.             AuthorList.Add("Praveen Kumar");  
  12.             AuthorList.Add("Raj Kumar");  
  13.             AuthorList.Add("Nipun Tomar");  
  14.             AuthorList.Add("Mahesh Chand");  
  15.             AuthorList.Add("Dinesh Beniwal");  
  16.   
  17.             // Contains - Check if an item is in the list    
  18.             if (AuthorList.Contains("Mahesh Chand"))  
  19.             {  
  20.                 Console.WriteLine("Author found!");  
  21.             }  
  22.   
  23.             // Find an item and replace it with new item  
  24.             int idx = AuthorList.IndexOf("Nipun Tomar");  
  25.             if (idx >= 0)  
  26.             {  
  27.                 AuthorList[idx] = "New Author";  
  28.             }  
  29.             Console.WriteLine("\nIndexOf ");  
  30.             foreach (var author in AuthorList)  
  31.             {  
  32.                 Console.WriteLine(author);  
  33.             }  
  34.   
  35.             // Find Last index of               
  36.             idx = AuthorList.LastIndexOf("Mahesh Chand");  
  37.             if (idx >= 0)  
  38.             {  
  39.                 AuthorList[idx] = "New Mahesh";  
  40.             }  
  41.             Console.WriteLine("\nLastIndexOf ");  
  42.             foreach (var author in AuthorList)  
  43.             {  
  44.                 Console.WriteLine(author);  
  45.             }  
  46.         }  
  47.     }  
  48. }  
The output from above listing is shown in below figure.
 
LastIndexOf 
 
Next >> C# List Tutorial


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.