Posted on 4/22/2025 7:44:22 AM by Admin

Data Structures – Lists in C# (Dynamic Arrays)

You are already familiar with the concept of arrays and multidimensional arrays. But, we cannot always know the elements of an array in advance. This is where the concept of lists, aka dynamic arrays, comes into play. The list is another fundamental data structure that comes in handy in various situations. The most important feature of the list is that it does not have a definite size. It is a powerful tool for managing data where the number of elements is not already known.

In this article, we will explore lists in C# and how to perform different operations on them.

What is a List?

A list is a collection of homogeneous data elements of an indefinite size. It is almost the same as an array but not with a specific size. The elements can be added or removed from a list dynamically. It is usually denoted by List<T> notation, which shows that you can create lists of any generic type, such as int, string, etc.

The lists provide significant benefits over arrays in certain situations. With fixed-sized arrays, you have to specify the size of an array at the time of declaration, and to add more elements, you have to redeclare a bigger array, copy the existing elements, and add the new elements to it. Whereas in lists, this resizing is handled behind the scenes. Suppose a list reaches its maximum capacity when you try adding more items. In that case, it automatically allocates a new, larger array, copying the existing elements and appending it with the new elements. This provides the developer with a seamless experience. Similarly, removing elements from a list shrinks its underlying storage and frees up the memory. This dynamicity makes the lists a better choice when it comes to storing an unpredictable number of elements.


System.Collections.Generic

To use lists in C#, you have to add a namespace, i.e., System.Collections.Generic, to which the List<T> belongs. Without adding this namespace, you cannot access or work with lists. So, let's add it to our program before moving forward to the operations on the lists:

Add the following line after using System;


using System.Collections.Generic;

Operations on Lists

C# provides many built-in functions and properties to perform different list operations. Let's explore these in this section:

List Declaration and Initialization

You can declare and initialize a list separately or combined as follows:

Declaring a List

To declare an empty list, follow the system below:


List<datatype> list_name = new List<datatype>();

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
    List<int> numbers = new List<int>(); //An empty list
    Console.ReadKey();
}
}

You can also specify the initial size of the list while declaring:


List<datatype> list_name = new List<datatype>(size);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
    List<string> a = names List<string>(5);
}
}

Initializing a List

You can initialize a list dynamically, but C# allows you to do so at the time of declaration as well. The following syntax can be used to initialize a list:


List<datatype> list_name = new List<datatype>(){item_1, item_2, … , item_N};

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
    List<string> names = new List<string>(){"James", "John", "Smith"};
    Console.ReadKey();
}
}

Finding the Length of a List

The number of items in a list defines its length. To find the length of a list, we use the Count property.

Syntax:


listname.Count;

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {      
    List<string> names = new List<string>(){"John", "James", "Smith"};
    Console.Write(names.Count); //Returns 3
    Console.ReadKey();
}
}

Adding Elements to the List

In C#, you can dynamically add the elements to the lists with the Add() or AddRange() methods.

The Add() Method

It adds a new element at the end of the list.

Syntax:


list_name.Add(new_item);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
    List<string> names = new List<string>(5);
    names.Add("John");
    names.Add("James");
    names.Add("Smith");
}
}

The AddRange() Method

To add multiple elements from an array or another list, you can use the AddRange() method.

Syntax:


array_name.AddRange(Collection_name);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {
    string[] usernames = {"John", "James", "Smith"};
    List<string> names = new List(5);
    names.AddRange(usernames);
}
}

Accessing List Items

Like arrays, you can access the list items using the index. The index of a list also starts from zero and ranges upto 1 – List_Items.

Syntax:


list_name[index];

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {    
    List<string> names = new List<string>(){"John", "James", "Smith"};;
    Console.Write(names[2]); //Prints Smith     
    Console.ReadKey();
}
}

Remember that you should not try to access an index that does not exist. Otherwise, you will encounter the ArgumentOutOfRange exception.

Inserting Elements in Lists

If you want to insert new elements to a specific index in a list, you can use Insert() and InsertRange() methods. When you insert an element at an index, the subsequent elements move to the right.

The Insert() Method

This method inserts a single element at the specified index.

Syntax:


list_name.Insert( index, value);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {    
    List<string> names = new List<string>(){"John", "James", "Smith"};
    names.Insert(1, "Medora"); //Inserts Medora at index 1 and moves James and Smith to the right.     
    Console.ReadKey();
}
}

The InsertRange() Method

The InserRange() method allows you to insert multiple elements using another list or an array at a particular index. The subsequent elements move to the right after all the elements have been inserted.

Syntax:


list_name.AddRange(index, collection_name);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {      
    string[] usernames = {"Jenna", "Jasmine", "Tony"};
    List<string> names = new List<string>(){"John", "James", "Smith"};;
    names.InsertRange(1, usernames); //Inserts all the elements in usernames array starting from index 1.     
    Console.ReadKey();
}
}

Removing Elements from a List

Besides adding, you can also remove the elements from a list using the built-in methods list Remove(), RemoveAt(), RemoveRange(), and Clear().

The Remove() Method

This method removes the specified item from the list. It moves the subsequent elements to the left.

Syntax:


listname.Remove(item);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {      
    List<string> names = new List<string>(){"John", "James", "Smith"};
    names.Remove("James"); //Removes James from the list
    Console.ReadKey();
}
}

The RemoveAt() Method

This method removes the item from the specified index.

Syntax:


list_name.RemoveAt(index);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {      
    List<string> names = new List<string>(){"John", "James", "Smith"};;
    names.RemoveAt(0); //Removes John from the list.
    Console.ReadKey();
}
}

The RemoveRange() Method

This method removes multiple elements from the list.

Syntax:


listname.RemoveRange(index_1, index_2, … , index_N);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {      
    List<string> names = new List<string>(){"John", "James", "Smith"};
    names.RemoveRange(0, 1); //Removes John and James. 
    Console.ReadKey();
}
}

The Clear() Method

This method removes all the items from the list.

Syntax:


listname.Clear();

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {      
    List<string> names = new List<string>(){"John", "James", "Smith"};
    names.Clear();
    Console.ReadKey();
}
}

Finding the Index of an Element

To find an index of an element, we use the IndexOf() method.

Syntax:


list_name.IndexOf(item);

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() { 
    List<string> names = new List<string>(){"John", "James", "Smith"};
    Console.Write(names.IndexOf("James"));
    Console.ReadKey();
}
}

Iterating Through a List

You can go through an entire list using the for or foreach loop like arrays.

Using for Loop

Syntax:


for(datatype variable = value; variable<listname.Count; variable++)
{
	//Some code here. 
}

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {      
    List<string> names = new List<string>(){"John", "James", "Smith"};
    for(int i=0; i<names.Count; i++)
    {
        Console.WriteLine(names[i]);
    }
    Console.ReadKey();
}
}

Using foreach Loop

Syntax:


foreach(datatype variable in listname)
{
	//Some code here. 
}

Example:


using System;
using System.Collections.Generic;
class DataStructures {
  static void Main() {      
    List<string>> names = new List<string>(){"John", "James", "Smith"};
    foreach(string name in names)
    {
        Console.WriteLine(name);
    }
    Console.ReadKey();
}
}

Lists are a useful data structure, and knowing how to manipulate them can help you in various situations. Besides what we have covered in this lesson, there is a lot more about lists in C#, which you can explore after excelling in the basic concepts. In the next article, we will learn about Stacks.


Data Structures -  Arrays in C#
Data Structures - Arrays in C#
Data Structures – Stacks in C# (LIFO)
Data Structures – Stacks in C# (LIFO)