✨ Shield now has support for Avalonia UI

Lists in C#: A Guide to Dynamic Data Storage

Feb 3, 2023 | .NET, C#

Introduction

In this article, we will discuss Lists in C#, a powerful and flexible data structure that allows you to store and manipulate collections of data. We will explore how to create, add, remove, and search items in a List, as well as some useful methods and properties available to manipulate Lists. Finally, we will provide examples to help you better understand how Lists work in C#.

What are Lists in C#?

Lists in C# are part of the System.Collections.Generic namespace and are used to store and manage a collection of objects. They are dynamic in size, allowing you to add or remove elements at runtime, and can store items of any data type, including custom types.

Declaring and Initializing Lists

There are two primary ways to declare and initialize a List in C#:

Using the List Constructor

You can create a new List by using the List constructor and specifying the data type of the elements

it will store. For example:

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

This creates a new List called numbers that will store integers.

Using Collection Initializers

You can also initialize a List with a collection initializer, which allows you to specify the initial elements within the declaration:

List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };

This creates a new List called fruits that stores strings, and initializes it with three elements.

Adding Items to a List

There are two primary methods to add items to a List:

Add() Method

The Add() method is used to add a single item to the end of the List:

fruits.Add("Grape");

AddRange() Method

The AddRange() method is used to add a collection of items to the end of the List:

List<string> moreFruits = new List<string> { "Mango", "Pineapple" };
fruits.AddRange(moreFruits);

Accessing Elements of a List

There are two primary ways to access elements in a List:

Using Indexers

You can access individual elements of a List using indexers, similar to arrays:

string firstFruit = fruits[0]; // Access the first element

ForEach Loop

You can also iterate through all the elements of a List using a foreach loop:

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Removing Items from a List

There are several methods to remove items from a List:

Remove() Method

The Remove() method removes the first occurrence of a specified item:

fruits.Remove("Banana");

RemoveAt() Method

The RemoveAt() method removes the item at a specified index:

fruits.RemoveAt(1); // Removes the second element

RemoveRange() Method

The RemoveRange() method removes a range of elements starting from a specified index:

fruits.RemoveRange(1, 2); // Removes the second and third elements

Sorting a List

There are two primary ways to sort a List in C#:

Using Sort() Method

The Sort() method sorts the elements of the List using the default comparer for the data type:

List<int> numbers = new List<int> { 8, 2, 6, 4, 1 };
numbers.Sort();

Using Comparison Delegate

You can also sort a List using a custom comparison delegate. This allows you to define your own sorting criteria:

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
names.Sort((x, y) => x.Length.CompareTo(y.Length)); // Sorts by string length

Searching in a List

There are two primary methods for searching elements in a List:

Find() Method

The Find() method searches for an element that matches a specified predicate:

int evenNumber = numbers.Find(x => x % 2 == 0); // Finds the first even number

FindAll() Method

The FindAll() method returns a new List containing all elements that match a specified predicate:

List<int> evenNumbers = numbers.FindAll(x => x % 2 == 0); // Finds all even numbers

List Capacity and Count

The Count property returns the number of elements in the List, while the Capacity property returns the current capacity of the List. The capacity is automatically increased as elements are added to the List.

int count = fruits.Count; // Returns the number of elements in the List
int capacity = fruits.Capacity; // Returns the current capacity of the List

Converting Lists to Arrays

You can convert a List to an array using the ToArray() method:

string[] fruitsArray = fruits.ToArray();

Working with ReadOnlyList

A ReadOnlyList is a wrapper around a List that provides a read-only view of the underlying List. This can be useful when you want to expose a List to external code without allowing modification:

ReadOnlyCollection<string> readOnlyFruits = fruits.AsReadOnly();

Examples

Let’s look at a couple of examples to demonstrate the use of Lists in C#.

Example 1: Basic List Operations

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> colors = new List<string> { "Red", "Blue", "Green" };
        colors.Add("Yellow");
        colors.AddRange(new List<string> { "Purple", "Orange" });

        Console.WriteLine("List of colors:");
        foreach (string color in colors)
        {
            Console.WriteLine(color);
        }

        Console.WriteLine("Removing 'Green' from the list...");
        colors.Remove("Green");

        Console.WriteLine("List of colors after removal:");
        foreach (string color in colors)
        {
            Console.WriteLine(color);
        }
    }
}

In this example, we create a List of strings, add elements to it, and then remove an element. The output will be:

// List of colors:
// Red
// Blue
// Green
// Yellow
// Purple
// Orange
// Removing 'Green' from the list...
// List of colors after removal:
// Red
// Blue
// Yellow
// Purple
// Orange

Example 2: Sorting, Searching and Filtering

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 4, 9, 2, 7, 5, 1, 8, 3, 6 };

        Console.WriteLine("Original list of numbers:");
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }

        numbers.Sort();
        Console.WriteLine("\nSorted list of numbers:");
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }

        int firstEvenNumber = numbers.Find(x => x % 2 == 0);
        Console.WriteLine($"\nFirst even number: {firstEvenNumber}");

        List<int> evenNumbers = numbers.FindAll(x => x % 2 == 0);
        Console.WriteLine("\nList of even numbers:");
        foreach (int number in evenNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

In this example, we create a List of integers, sort the elements, search for the first even number, and filter the list to get all even numbers. The output will be:

Original list of numbers:
4
9
2
7
5
1
8
3
6

Sorted list of numbers:
1
2
3
4
5
6
7
8
9

First even number: 2

List of even numbers:
2
4
6
8

Conclusion

In this article, we discussed Lists in C#, a versatile data structure that allows you to store and manipulate collections of data. We explored various methods to create, add, remove, sort, and search elements in a List, as well as working with ReadOnlyList and converting Lists to arrays. The provided examples should help you better understand how to work with Lists in C#.

FAQs

  1. What is the main difference between a List and an array in C#?The main difference is that a List is dynamic in size, allowing you to add or remove elements at runtime, while an array has a fixed size.
  2. How can I remove all elements from a List?You can use the Clear() method to remove all elements from a List: fruits.Clear();
  3. Can a List store items of different data types?A List can only store items of a single data type. However, you can create a List of type object to store items of different types, but you will need to cast them to their appropriate types when accessing them.
  4. How do I check if a List contains a specific item?You can use the Contains() method to check if a List contains a specific item: bool exists = fruits.Contains("Banana");
  5. Can I create a List of custom objects?Yes, you can create a List of custom objects. Just specify the custom object type when declaring the List: List<MyCustomClass> customList = new List<MyCustomClass>();

You May Also Like