Reading All C# List Items
C# List<T> class provides methods and properties to create a list of objects and read them back. C# List is a generic class. Before using the List<T> class, you must import the following namespace.
using System.Collections.Generic;
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 list items and prints them on the console.
foreach (string author in AuthorList)
{
Console.WriteLine(author);
}
We can also use a var keyword to that can store and data type.
foreach (var author in AuthorList)
{
Console.WriteLine(author);
}
The following code snippet creates a new list, reads all of its items, and displays it on the console.
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// 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);
}
}
}
}
The output from the above listing is shown in the below figure.
Next >> C# List Tutorial