How To Find An Item In C# List

C# List<T> class provides methods and properties to create a list of objects (classes). The Contains method checks if the specified item is already exists 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 following code snippet checks if an item is already exits.  
  1. if (AuthorList.Contains("Mahesh Chand"))  
  2.     AuthorList.Remove("Mahesh Chand");
The IndexOf method returns the first index of an item if found in the List.
  1. int idx = AuthorList.IndexOf("Nipun Tomar");  
The LastIndexOf method returns the last index of an item if found in the List. 
  1. idx = AuthorList.LastIndexOf("Mahesh Chand");  
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.             // Find Last index of               
  35.             idx = AuthorList.LastIndexOf("Mahesh Chand");  
  36.             if (idx >= 0)  
  37.             {  
  38.                 AuthorList[idx] = "New Mahesh";  
  39.             }  
  40.             Console.WriteLine("\nLastIndexOf ");  
  41.             foreach (var author in AuthorList)  
  42.             {  
  43.                 Console.WriteLine(author);  
  44.             }  
  45.         }  
  46.     }  
  47. }  
The output of above Listing looks like Figure 1.
 
C# List 
 


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.