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,
usingSystem;usingSystem.Collections.Generic;classProgram{publicstaticvoidMain() { // create a list named subjects that contain 2 elements var subjects =newList<string>();subjects.Add("English");subjects.Add("Math"); }}
OR
usingSystem;usingSystem.Collections.Generic;classProgram{publicstaticvoidMain() { //create a list named subjects that contain 2 elements //object initialization syntaxvar subjects =newList<string>() { "English","Math" }; }}
Access the List Elements
We can access List using index notation []. For example,
usingSystem;usingSystem.Collections.Generic;classProgram{publicstaticvoidMain() {List<string> languages =newList<string>() { "Python","Java" }; // access the first and second elements of languages listConsole.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,
usingSystem;usingSystem.Collections.Generic;classProgram{publicstaticvoidMain() {List<string> albums =newList<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
usingSystem;usingSystem.Collections.Generic;classProgram{publicstaticvoidMain() {List<string> albums =newList<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: