English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# List (List)

List<T> is a collection of strongly-typed objects that can be accessed by index and has methods for sorting, searching, and modifying the list. It is the generic version of ArrayList under the System.Collection.Generic namespace.

List<T> Features

  • List<T> is equivalent to ArrayList and implements IList<T>.

  • It is under the System.Collection.Generic namespace.

  • List<T> can contain elements of a specified type. It provides compile-time type checking and does not perform boxing./Unboxing, because it is generic.

  • You can use Add(), AddRange() methods or collection-Add elements using initializer (collection initializer) syntax

  • Elements can be accessed by passing an index, for example myList[0]. The index starts from zero.

  • List<T> is faster in execution and less prone to errors compared to ArrayList.

Create List

List<T> is a generic collection, so you need to specify the type parameter of the data type it can store. The following example shows how to create a list and add elements.

List<int> primeNumbers = new List<int>();
primeNumbers.Add(1); // Add elements using add() method
primeNumbers.Add(3);
primeNumbers.Add(5);
primeNumbers.Add(7);
var cities = new List<string>();
cities.Add("New York");
cities.Add("London");
cities.Add("Mumbai");
cities.Add("Chicago");
cities.Add(null);// Reference type lists allow null
//Use collection-Add elements using initializer syntax
var bigCities = new List<string>()
                    {
                        "New York",
                        "London",
                        "Mumbai",
                        "Chicago"                    
                    });

In the above example,

List<int> primeNumbers = new List<int>();

Create a list of int type. Similarly, cities and bigcity are List of strings. Then you can add elements to the list using the add() method or collection initializer syntax.

You can also use collection-Add elements of custom classes using initializer syntax. The following example adds objects of the Student class to List<Student>.

var students = new List<Student>() { 
                new Student(){ Id = 1, Name="Bill"},
                new Student(){ Id = 2, Name="Steve"},
                new Student(){ Id = 3, Name="Ram"},
                new Student(){ Id = 4, Name="Abdul"
            });

Add an array to the List

Use the AddRange() method to add all elements from an array or another collection to the List.

AddRange() Signature:

 void AddRange(IEnumerable<T> collection)
string[] cities = new string[3]{ "Mumbai", "London", "New York" };
var popularCities = new List<string>();
// Add array to list
popularCities.AddRange(cities);
var favouriteCities = new List<string>();
// Add list 
favouriteCities.AddRange(popularCities);

Access List

You can access the List/foreach loop and using LINQ query to access the list. The index of the list starts from zero. Pass the index in brackets to access a single list item, as with arrays. Iterate over the List<T> collection using foreach or for loops.

List<int> numbers = new List<int>() { 1, 2, 5, 7, 8, 10 });
Console.WriteLine(numbers[0]); // Engraving1
1] // Engraving2
2] // Engraving5
3] // Engraving7
// Using foreach LINQ method
numbers.ForEach(num => Console.WriteLine(num + ", ")//Print1,2,5,7,8,10,
// Using a for loop
for(int i = 0; i < numbers.Count;++)
    Console.WriteLine(numbers[i]);

Accessing a list with LINQ

List<T> implements the IEnumerable interface. Therefore, we can use LINQ query syntax or method syntax to query the list, as shown below.

var students = new List<Student>() { 
                new Student(){ Id = 1, Name="Bill"},
                new Student(){ Id = 2, Name="Steve"},
                new Student(){ Id = 3, Name="Ram"},
                new Student(){ Id = 4, Name="Abdul"
            });
//Get all students named "Bill"
var result = from s in students
	     where s.Name == "Bill"
	     select s;
foreach(var student in result)
    Console.WriteLine(student.Id + "	" + student.Name);

Inserting elements in a List

Use the Insert() method to insert the element into the collection at the specified index of List<T>.

Insert() Signature:

void Insert(int index, T item);
var numbers = new List<int>(){ 10, 20, 30, 40 };
numbers.Insert(1, 11);// Insert at the first index11At10After that.
foreach (var num in numbers)
    Console.Write(num);

Delete elements from the list (List)

Use the Remove() method to delete the first occurrence of the specified element from the List<T> collection. Use the RemoveAt() method to delete elements from the specified index. If there is no element at the specified index, an ArgumentOutOfRangeException will be thrown.

Remove() Signature

 bool Remove(T item)

RemoveAt() Signature

void RemoveAt(int index)
var numbers = new List<int>(){ 10, 20, 30, 40, 10 });
numbers.Remove(10); // Delete from the list10
numbers.RemoveAt(2); //Delete the third element (index starts from 0)
//numbers.RemoveAt(10); //Throw ArgumentOutOfRangeException
foreach (var el in intList)
    Console.Write(el); // Output 20 30

Check elements in the list (List)

Use the Contains() method to determine if an element is in the List<T>.

var numbers = new List<int>(){ 10, 20, 30, 40 };
numbers.Contains(10); // Return true
numbers.Contains(11); // Return false
numbers.Contains(20); // Return true

List <T> Class Hierarchy

The following figure illustrates the List<T> hierarchy.

List <T> Class Properties and Methods

The following table lists the important properties and methods of the List<T> class:

PropertiesUsage
ItemsGet or set the element at the specified index.
CountReturn the total number of elements existing in List <T>.
MethodUsage
AddAdd an element to the end of List <T>.
AddRangeAdd the elements of the specified collection to the end of List <T>.
BinarySearchSearch for the element and return the index of the element.
ClearRemove all elements from List <T>.
ContainsCheck if the specified element exists in List <T>.
FindFind the first element according to the specified predicate function.
ForeachTraverse the List <T>.
InsertInsert elements at the specified index in the List <T>.
InsertRangeInsert elements from another collection at the specified index.
RemoveRemove the first occurrence of the specified element.
RemoveAtRemove the element at the specified index.
RemoveRangeRemove all elements that match the provided predicate function.
SortSort all elements.
TrimExcessSet the capacity to the actual number of elements.
TrueForAllDetermine whether each element in the List <T> matches the specified predicate-defined condition.