Skip to main content

How to Use List in Csharp

This article will break down everything you need to know, complete with examples to help you get started.

What Is a List<T>?

In simple terms, a List<T> is a resizable array in C#. Unlike arrays, which have a fixed size after creation, a List<T> expands or shrinks as needed. The <T> denotes that it is a generic type, meaning you can specify the data type it holds.

Here are some key benefits of using List<T>:

  • Resizable: No need to predefine its capacity.
  • Strongly-Typed: Ensures the type of data it holds matches the specified type of <T>.
  • Rich Functionality: Comes with built-in methods like Add, Remove, Sort, and more.

For an overview of basic C# structures, check out this guide to C# Variables.

Getting Started: How to Use List<T>

Creating a List<T>

To create a List<T>, simply declare it and specify the type it will hold. Here’s a basic example:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initialize a list of integers
        List<int> numbers = new List<int>();

        // Add values to the list
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);

        // Display the list
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

Explanation:

  1. You use new List<int>() to initialize the list.
  2. The Add method inserts items into the list.
  3. The foreach loop iterates through and prints each item.

Accessing and Modifying Items

You can access elements using an index, just like an array. Here's an example:

List<string> names = new List<string>() { "Alice", "Bob", "Charlie" };

Console.WriteLine(names[0]); // Outputs: Alice

names[1] = "David"; // Replaces "Bob" with "David"
Console.WriteLine(names[1]); // Outputs: David

Key Points:

  • Indexes start at 0.
  • You can directly replace an item by specifying its index.

Common Methods

Here are some useful methods you’ll frequently use:

  1. Add: Adds an element at the end of the list.
  2. Insert: Adds an element at a specific index.
  3. Remove and RemoveAt: Deletes items.
  4. Count: Returns the number of elements in the list.

Let’s see a practical example:

List<string> cities = new List<string>();

// Add cities
cities.Add("New York");
cities.Add("Los Angeles");
cities.Add("Chicago");

// Insert a city at position 1
cities.Insert(1, "Houston");

// Remove a city
cities.Remove("Los Angeles");

// Display cities
foreach (string city in cities)
{
    Console.WriteLine(city);
}

Output:

New York
Houston
Chicago

For related sorting techniques, refer to the article on Sorting with Lambdas.

Advanced Features of List<T>

Sorting with .Sort()

Sorting becomes simple with the Sort method:

List<int> numbers = new List<int>() { 5, 1, 4, 2, 3 };

numbers.Sort();

foreach (int number in numbers)
{
    Console.WriteLine(number);
}

Output:

1
2
3
4
5

Filtering with .FindAll()

Use FindAll to filter items based on a condition. For instance:

List<int> numbers = new List<int>() { 5, 1, 4, 2, 3 };

List<int> evens = numbers.FindAll(x => x % 2 == 0);

foreach (int even in evens)
{
    Console.WriteLine(even);
}

Output:

4
2

Checking Items with .Contains()

You can check if an item exists with Contains:

List<string> fruits = new List<string>() { "Apple", "Banana", "Cherry" };

if (fruits.Contains("Banana"))
{
    Console.WriteLine("Banana is in the list!");
}

Performance Considerations

While List<T> is flexible, keeping performance in mind is key. For instance:

  • Adding many items at once? Predefine the capacity with the Capacity property.
  • For highly frequent operations, consider alternatives like LinkedList<T> or HashSet<T>.

Explore the use of access scopes and modifiers in this supplementary post about C# access modifiers.

Conclusion

The List<T> in C# unlocks endless possibilities for managing collections dynamically. Its rich functionality ensures efficiency and simplicity for novice and experienced developers alike. Practice working with various methods to master its potential.

For more on related topics, check out this guide to working with C# files. Experiment with these examples and see how a List<T> can simplify your next project.

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...