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.
- using System.Collections.Generic;
The following code snippet checks if an item is already exits.
- if (AuthorList.Contains("Mahesh Chand"))
- AuthorList.Remove("Mahesh Chand");
The IndexOf method returns the first index of an item if found in the List.
- int idx = AuthorList.IndexOf("Nipun Tomar");
The LastIndexOf method returns the last index of an item if found in the List.
- idx = AuthorList.LastIndexOf("Mahesh Chand");
The following code snippet shows how to use the Contains, the IndexOf and the LastIndexOf methods.
- using System;
- using System.Collections.Generic;
- namespace ConsoleApp1
- {
- class Program
- {
- static void Main(string[] args)
- {
- 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");
-
-
- if (AuthorList.Contains("Mahesh Chand"))
- {
- Console.WriteLine("Author found!");
- }
-
-
- int idx = AuthorList.IndexOf("Nipun Tomar");
- if (idx >= 0)
- {
- AuthorList[idx] = "New Author";
- }
- Console.WriteLine("\nIndexOf ");
- foreach (var author in AuthorList)
- {
- Console.WriteLine(author);
- }
-
- idx = AuthorList.LastIndexOf("Mahesh Chand");
- if (idx >= 0)
- {
- AuthorList[idx] = "New Mahesh";
- }
- Console.WriteLine("\nLastIndexOf ");
- foreach (var author in AuthorList)
- {
- Console.WriteLine(author);
- }
- }
- }
- }
The output of above Listing looks like Figure 1.