Reader Level:
Articles

How to get last index of an item in a C# List

By Mahesh Chand on Jul 06, 2012
The LastIndexOf method returns the last index of an item if found in the List.
  • 0
  • 0
  • 24325

The IndexOf method returns the first index of an item if found in the List.

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. 

List<string> AuthorList = new List<string>();
AuthorList.Add("Mahesh Chand");
AuthorList.Add("Praveen Kumar");
AuthorList.Add("Raj Kumar");
AuthorList.Add("Nipun Tomar");
AuthorList.Add("Mahesh Chand");
AuthorList.Add("Dinesh Beniwal");
            
// Contains - Check if an item is in the list  
if (AuthorList.Contains("Mahesh Chand")) 
{
    Console.WriteLine("Author found!");
}        

// Find an item and replace it with new item
int idx = AuthorList.IndexOf("Nipun Tomar");
if (idx >= 0)
{
    AuthorList[idx] = "New Author";
}
Console.WriteLine("\nIndexOf ");
foreach (var author in AuthorList)
{
    Console.WriteLine(author);
}


// Find Last index of             
idx = AuthorList.LastIndexOf("Mahesh Chand");
if (idx >= 0)
{
    AuthorList[idx] = "New Mahesh";
}
Console.WriteLine("\nLastIndexOf ");
foreach (var author in AuthorList)
{
    Console.WriteLine(author);
}

Mahesh Chand

C# Corner founder, 10-times Microsoft MVP, technical author, and software architect. Mahesh authored his first book, A Programmer’s Guide to ADO.NET in C# with APress at the age of 25. C# Corner is a memb... Read more

COMMENT USING