List<T> is a class that contains multiple objects of the same data type that can be accessed using an index. For example,
Create a List
To create List<T> in C#, we need to use the System.Collections.Generic namespace. Here is how we can create List<T>.For example,
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// create a list named subjects that contain 2 elements
var subjects = new List<string>();
subjects.Add("English");
subjects.Add("Math");
}
}
OR
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
//create a list named subjects that contain 2 elements
//object initialization syntax
var subjects = new List<string>()
{
"English",
"Math"
};
}
}
Access the List Elements
We can access List using index notation []. For example,
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<string> languages = new List<string>() { "Python", "Java" };
// access the first and second elements of languages list
Console.WriteLine("The first element of the list is " + languages[0]);
Console.WriteLine("The second element of the list is " + languages[1]);
}
}
Iterate the List
In C#, we can also loop through each element of List<T> using a for loop. For example,
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<string> albums = new List<string>() { "Red", "Midnight", "Reputation" };
// iterate through the albums list
for (int i = 0; i < albums.Count; i++)
Console.WriteLine(albums[i]);
}
}
Note: The Count property returns the total number of elements inside the list.
OR
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<string> albums = new List<string>() { "Red", "Midnight", "Reputation" };
// iterate through the albums list
foreach (string album in albums)
Console.WriteLine(album);
}
}
Basic Operations on List
The List<T> class provides various methods to perform different operations on List. We will look at some commonly used List operations in this tutorial: