C# List (with Examples)

Learn via video courses
Topics Covered

Overview

The list in C# is a fundamental data structure provided by the .NET Framework that provides a dynamic, resizable collection of elements. It comes under the System.Collections.Generic namespace and offers numerous advantages over traditional arrays. C# List is based on the concept of a dynamic array, which expands or contracts as elements are added or removed. This flexibility makes it a viable alternative for handling the collection of elements in C#.

What is C# List?

C# List<T> is a generic class that represents a dynamic, resizable collection of elements of the type T. It is part of the System.Collections.Generic namespace in the .NET Framework. It is part of the System.Collections.Generic namespace and provides a flexible and efficient way to manage collections of items, such as integers, strings, custom objects, and more. The letter T in the list represents a specific type of element. This type is passed as a parameter during runtime. A List in C# is comparable to an array, but it provides more flexibility by automatically resizing itself when entries are added or removed, eliminating the need for manual memory management.

Characteristics

  • List<T>, unlike arrays, can be dynamically resized, which means it can expand or shrink based on the number of elements it contains.
  • List<T> accepts null as a valid value for reference types and enables duplicate elements to be added.
  • When the number of elements in the List<T> reaches its current capacity, it automatically increases the capacity by reallocating the internal array and copying existing elements to the new array before adding the new element.
  • List<T> is the generic equivalent to the ArrayList class. It implements the IList<T> generic interface.
  • List<T> provides equality and ordering comparers, which makes it useful for custom sorting and searching operations.
  • The list class is not sorted by default, and elements are accessed using zero-based indexing. The first element is at index 0, the second at index 1, and so on.
  • On a 64-bit system, you can expand the maximum capacity of List<T> objects to 2 billion elements by setting the enabled property of the configuration element to true in the run-time environment.

Constructors

ConstructorDescription
List<T>()The List<T> class's List<T>() constructor creates a new instance of the class with an empty state and a default initial capacity.
List<T>(IEnumerable<T>)The List<T> class's constructor List<T>(IEnumerable<T> collection) creates a new instance of the class with elements copied from the specified collection. The new instance has sufficient capacity to accommodate all the elements copied from the collection.
List<T>(Int32)The List<T> class's constructor List<T>(Int32) initializes a new instance of the class that is initially empty and has a user-specified initial capacity.

Methods

MethodDescription
Add(T)It adds an element to the end of a List<T>.
AddRange(IEnumerable<T>)It appends the elements of the specified collection to the end of the existing List.
AsReadOnly()It returns a read-only wrapper around the original List, which allows you to provide read-only access to the elements in the List.
BinarySearch()This method performs a binary search on the sorted List to find the index of a specified value.
Clear()This method removes all items from the List.
Contains(T)This method checks whether a specific value of type T exists in the List.
ConvertAll(Converter)This method converts the current List<T>'s elements to another type and returns a list with the converted elements.
ToArray()This method converts a List to an array of the same type as the List. It creates a new array and copies all the elements from the List to the new array.
Sort()This method sorts the elements in the List in ascending order based on their natural ordering.
Reverse()This method is used to reverse the order of the items in a C# List.
CopyTo()This method copies the elements of the List to an existing one-dimensional array of type T.
Equals(Object)This method determines whether the specified object is equal to the current object.
GetHashCode()It serves as the default hash function.
Exists(Predicate<T>)This method allows you to determine whether the List contains elements that match the conditions defined by the specified predicate.
GetEnumerator()This method returns an enumerator that allows you to iterate through the elements of the List in a forward-only manner.
Remove(T)This method is used to remove the first occurrence of a specific object from the List<T>.
RemoveAll(Predicate<T>)This method allows you to remove all elements from the List that match the conditions defined by the specified predicate.
RemoveAt(Int32)This method is used to remove the element at the specified index of the List<T>.
RemoveRange(Int32, Int32)This method is used to remove a specified range of elements from the List<T>.
Find(Predicate<T>)This method allows you to search for an element that matches the conditions defined by the specified predicate, and it returns the first occurrence within the entire List.
FindIndex()This method allows you to search for an element that matches the conditions defined by the specified predicate, and it returns the zero-based index of the first occurrence within the List or a portion of it. If no element in the List satisfies the condition, the method returns -1.
FindAll(Predicate<T>)This method List retrieves all the elements from the List that satisfy the conditions specified by the provided predicate.
FindLastIndex()This method searches for an element that matches the conditions defined by the specified predicate, and it returns the index of the last occurrence of that element within the List or a specified portion of it.
FindLast(Predicate<T>)This method finds the last element in the List that satisfies the condition specified by the provided predicate. If no element in the List satisfies the condition, the method returns the default value for the type (null in the case of reference types).
TrueForAll(Predicate<T>)This method determines whether every element in the List matches the conditions defined by the specified predicate.
ToString()This method returns a string that represents the current List object.

Create a List in C#

To create a List in C#, perform the following steps:

  • Include the System.Collections.Generic namespace to access the List<T> class.
  • Declare a variable of type List<T>, providing the data type T for the elements you wish to store in the list.
  • Initialize the list using the new keyword.

Here's an example of creating an integer List:

Output

In the above example, we created a List of integers named marks that contain three elements (60, 80, 75).

Add an item to a C# List

You can use the Add() function to add an item to a C# List. The Add() function adds an element to the end of a List. If the List is of a generic type, you must give an item of the correct data type for the List. Here's an example of adding an element to the C# List:

Output

In the above example, we created a List of string-named subjects and added the three elements (Hindi, English, and Maths).

Loop through a C# List items

The C# List is a collection of elements. You can use different loops to loop through the elements in a C# List, such as for, while, or the foreach loop. The foreach loop is a convenient way to iterate through the elements of a List without the need for an explicit index. Here's how to use a foreach loop to loop through a List

Example:

Output

In the above example, we created a List of string-named subjects and added the three elements (Hindi, English, and Maths). Then, we use a foreach loop to iterate through the List and print each subject's name.

Insert an item at a position in a C# List

The Insert method adds an element to the C# list at the specified index, shifting existing elements to the right in order to create space for the new item.

Example:

Output:

Insert multiple items from one C# List into another C# List

When you want to insert multiple items from another collection into an existing List, use the InsertRange method. It avoids the need to add elements one by one using the Insert method.

Example:

Output:

Remove an item from a C# List

In C#, the List<T> class provides many methods for removing items from the list, including Remove, RemoveAt, RemoveRange, and Clear. Let's understand each method's functionality with the example:

1. Remove method: This method removes the first occurrence of a given item from the List. For example, the code below removes the first occurrence of 'English'.

Output:

2. RemoveAt method: This method removes the item at the given index position in the List. For example, the code below removes the item at the 1st position.

Output:

3. RemoveRange method: This method removes a range of items from the List, starting from a specified index and removing a specified number of elements. For example, the code below removes two items starting at the 1st position.

Output:

4. Clear method: This method removes all items from the List. For example, the code below removes all items from the List.

Output:

Check if an item exists in a C# List

The IndexOf and LastIndexOf methods in the C# List allow you to find the position of an item in the list. The IndexOf method finds the first occurrence of the specified item in the List and returns its index. If the item is not found, it returns -1, whereas the LastIndexOf method finds the last occurrence of the specified item in the List.

Example:

Output:

Sort a C# List

The Sort method, which is available for the List class, can be used to sort a C# List. The Sort method sorts the elements in the List in ascending order based on their natural ordering. To sort a List, use the Sort method as follows:

Output:

Reverse a C# List

The Reverse method, which is available for the List class, can be used to reverse the items in a C# List. The Reverse method flips the List from its original order by reversing the order of the elements in the List. To reverse a List, use the Reverse method as follows:

Output:

Import items to a C# List from another List

To import items from one list into another, we can utilise the AddRange() method of List. However, be certain that the item types in both lists are the same. For example, the following code snippet creates two List objects and copies all entries of second_list into first_list.

Output:

Convert a C# List to an array

You can use the ToArray() method of the List class to convert a C# List to an array. The ToArray() method creates a new array containing all of the List's elements in the same order as they appear in the List. Example:

Output:

Join two C# Lists

The AddRange() method in C# List allows you to join two Lists. The AddRange() method appends all of the elements from the source List to the end of the destination List.

Example:

Output:

Conclusion

  • The list in C# is a fundamental data structure provided by the .NET Framework that provides a dynamic, resizable collection of elements.
  • The Add() function adds an element to the end of a List.
  • The foreach loop in C# is a convenient way to iterate through the elements of a List without the need for an explicit index.
  • The Insert() method adds an element to the C# list at the specified index, shifting existing elements to the right in order to create space for the new item.
  • The InsertRange() method can be used to insert multiple items from another collection into an existing List.
  • In C#, the List class provides many methods for removing items from the list, including Remove(), RemoveAt(), RemoveRange(), and Clear().
  • The IndexOf() and LastIndexOf() methods in the C# List allow you to find the position of an item in the list.