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. // Contains - Check if an item is in the list
  17. if (AuthorList.Contains("Mahesh Chand"))
  18. {
  19. Console.WriteLine("Author found!");
  20. }
  21. // Find an item and replace it with new item
  22. int idx = AuthorList.IndexOf("Nipun Tomar");
  23. if (idx >= 0)
  24. {
  25. AuthorList[idx] = "New Author";
  26. }
  27. Console.WriteLine("\nIndexOf ");
  28. foreach (var author in AuthorList)
  29. {
  30. Console.WriteLine(author);
  31. }
  32. // Find Last index of
  33. idx = AuthorList.LastIndexOf("Mahesh Chand");
  34. if (idx >= 0)
  35. {
  36. AuthorList[idx] = "New Mahesh";
  37. }
  38. Console.WriteLine("\nLastIndexOf ");
  39. foreach (var author in AuthorList)
  40. {
  41. Console.WriteLine(author);
  42. }
  43. }
  44. }
  45. }
The output of above Listing looks like Figure 1.
C# List
Next >> C# List Tutorial