Examples of C# Lists and List Operations

Explore practical examples of C# Lists and List Operations to enhance your programming skills.
By Taylor

Introduction to C# Lists and List Operations

In C#, a List is a collection that can grow and shrink dynamically as you add or remove items. Lists are part of the System.Collections.Generic namespace and are ideal for storing a sequence of elements. They provide a variety of built-in methods to manipulate the data, making them a powerful tool for any developer. In this article, we’ll explore three diverse examples of C# Lists and List Operations that will help you understand their functionality better.

Example 1: Managing a Shopping List

In this example, we’ll create a simple shopping list application that allows users to add, remove, and display items. This is a practical use case for Lists, as you often need to manage collections of items dynamically.

using System;
using System.Collections.Generic;

class ShoppingList
{
    static void Main()
    {
        List<string> shoppingList = new List<string>();

        // Adding items to the shopping list
        shoppingList.Add("Milk");
        shoppingList.Add("Bread");
        shoppingList.Add("Eggs");

        // Displaying the shopping list
        Console.WriteLine("Current Shopping List:");
        foreach (string item in shoppingList)
        {
            Console.WriteLine(item);
        }

        // Removing an item
        shoppingList.Remove("Bread");
        Console.WriteLine("\nUpdated Shopping List:");
        foreach (string item in shoppingList)
        {
            Console.WriteLine(item);
        }
    }
}

In this code, we create a list called shoppingList. We add three items to it and display the list using a foreach loop. After that, we remove “Bread” and display the updated list.

Notes

  • You can easily modify this example to allow user input for adding items.
  • Consider adding error handling for cases when removing an item that doesn’t exist.

Example 2: Sorting a List of Names

Sorting a list is a common task in programming. In this example, we will create a list of names and sort them alphabetically. This showcases how to use the Sort method, which is a built-in List operation.

using System;
using System.Collections.Generic;

class SortNames
{
    static void Main()
    {
        List<string> names = new List<string>()
        {
            "Zara",
            "Alex",
            "John",
            "Mia"
        };

        Console.WriteLine("Names before sorting:");
        DisplayList(names);

        // Sorting the names
        names.Sort();
        Console.WriteLine("\nNames after sorting:");
        DisplayList(names);
    }

    static void DisplayList(List<string> list)
    {
        foreach (string name in list)
        {
            Console.WriteLine(name);
        }
    }
}

Here, we initialize a list of names and display them before and after sorting. The Sort method sorts the names in ascending order.

Notes

  • The Sort method modifies the original list, so if you need to keep the unsorted version, consider creating a copy first.
  • You can also sort objects based on specific properties by implementing IComparer.

Example 3: Finding the Maximum Value in a List

In this example, we will create a list of integers and find the maximum value. This demonstrates how you can perform operations to analyze data within a list.

using System;
using System.Collections.Generic;

class MaxValueFinder
{
    static void Main()
    {
        List<int> numbers = new List<int>()
        {
            10,
            25,
            3,
            45,
            12
        };

        Console.WriteLine("Numbers in the list:");
        DisplayList(numbers);

        // Finding the maximum value
        int maxValue = FindMaxValue(numbers);
        Console.WriteLine($"\nMaximum Value: {maxValue}");
    }

    static void DisplayList(List<int> list)
    {
        foreach (int number in list)
        {
            Console.WriteLine(number);
        }
    }

    static int FindMaxValue(List<int> list)
    {
        int max = list[0];
        foreach (int number in list)
        {
            if (number > max)
            {
                max = number;
            }
        }
        return max;
    }
}

In this code, we create a list of integers, display them, and then find the maximum value using a simple loop.

Notes

  • You could enhance this example by using LINQ with list.Max() for a more concise solution.
  • Consider adding functionality to handle empty lists to avoid exceptions.