Reading List Items 

The List<T> is a collection. We can use the foreach loop to go through all the items and read them. The following code snippet reads all items of a list and prints them on the console. 

foreach (string author in AuthorList)
{
    Console.WriteLine(author);
}

We can also use a var keyword for any kind of data type. 

foreach (var author in AuthorList)
{
    Console.WriteLine(author);
}

The following code snippet creates a new list and reads all of its items and displays on the console. 

public void CreateList()
{
    // Create a list of strings
    List<string> AuthorList = new List<string>();
    AuthorList.Add("Mahesh Chand");
    AuthorList.Add("Praveen Kumar");
    AuthorList.Add("Raj Kumar");
    AuthorList.Add("Nipun Tomar");
    AuthorList.Add("Dinesh Beniwal");

    // Read all data
    Console.WriteLine("Authors List");
    foreach (var author in AuthorList)
    {
        Console.WriteLine(author);
    }
}


Download Free book: Programming List with C#

 

Next Recommended Readings