List
What is a List?
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
Access the List Elements
We can access List using index notation []. For example,
Iterate the List
In C#, we can also loop through each element of List<T> using a for loop. For example,
Note: The Count property returns the total number of elements inside the list.
OR
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:
Add Elements
Insert Elements
Remove Elements
For details, see:
Last updated