C# List class provides methods and properties to create a list of objects (types). For example, the IndexOf method returns the first index of an item if found in the List.
The list is a generic class. Therefore, youore using the List<T> class, you must import the following namespace.
Using System.Collections.Generic;
Here is an example of the IndexOf method.
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"); foreach (var author in AuthorList) { Console.WriteLine(author); } Console.WriteLine("-------------"); // 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); } } } }
The output from the above listing is as below.
Continue Reading >> C# List Tutorial