Mastering C# Collections: A Step-by-Step Guide with Code Examples

Introduction

Collections in C# are a vital part of everyday programming. They allow you to store, manage, and manipulate groups of data efficiently. Whether you’re working with lists, queues, stacks, or dictionaries, understanding how to use collections will significantly enhance your ability to manage data in C#. In this tutorial, we will explore some of the most commonly used collections in C# along with practical examples to help you understand how to implement them in your own programs.

What are Collections in C#?

Collections in C# are objects that represent a group of objects. Unlike arrays, which have a fixed size, collections are dynamic and can grow or shrink as needed. They are part of the System.Collections and System.Collections.Generic namespaces.

Types of C# Collections

In C#, collections can be broadly categorized into the following types:

  1. List: A dynamic array that can store elements of the same type.
  2. Dictionary: A collection of key-value pairs where keys are unique.
  3. Queue: A collection based on the First-In-First-Out (FIFO) principle.
  4. Stack: A collection based on the Last-In-First-Out (LIFO) principle.
  5. HashSet: A collection of unique elements with no specific order.

We will explore each of these collections in detail with step-by-step code examples.

Step-by-Step Guide to C# Collections

1. List Collection

A List in C# is a dynamic array that can grow and shrink as you add or remove elements. It stores elements of the same data type.

Code Example:

// File: ListExample.cs
using System;
using System.Collections.Generic;

namespace CollectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a list of integers
            List numbers = new List();

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

            // Display the elements in the list
            Console.WriteLine("Elements in List:");
            foreach (var number in numbers)
            {
                Console.WriteLine(number);
            }

            // Remove an element
            numbers.Remove(2);

            Console.WriteLine("After Removing 2:");
            foreach (var number in numbers)
            {
                Console.WriteLine(number);
            }
        }
    }
}

Explanation:

  • We create a list of integers.
  • Add elements to the list using the Add method.
  • Use a foreach loop to print the elements in the list.
  • Remove an element using the Remove method.

2. Dictionary Collection

A Dictionary in C# stores key-value pairs. Each key in a dictionary must be unique, but the values can be duplicated.

Code Example:

// File: DictionaryExample.cs
using System;
using System.Collections.Generic;

namespace CollectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a dictionary of string keys and integer values
            Dictionary students = new Dictionary();

            // Add elements to the dictionary
            students.Add("John", 85);
            students.Add("Sarah", 90);
            students.Add("Bob", 75);

            // Access dictionary elements using keys
            Console.WriteLine($"John's Score: {students["John"]}");

            // Update a value in the dictionary
            students["John"] = 95;

            // Display all key-value pairs
            Console.WriteLine("All Students:");
            foreach (var student in students)
            {
                Console.WriteLine($"Name: {student.Key}, Score: {student.Value}");
            }
        }
    }
}

Explanation:

  • We create a dictionary with string keys and int values.
  • Add elements to the dictionary using the Add method.
  • Access and update values using the key.
  • Use a foreach loop to iterate through the dictionary's key-value pairs.

3. Queue Collection

A Queue in C# is a First-In-First-Out (FIFO) collection. The first element added is the first element to be removed.

Code Example:

// File: QueueExample.cs
using System;
using System.Collections.Generic;

namespace CollectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a queue of strings
            Queue tasks = new Queue();

            // Add elements to the queue
            tasks.Enqueue("Task 1");
            tasks.Enqueue("Task 2");
            tasks.Enqueue("Task 3");

            // Process and remove elements from the queue
            Console.WriteLine("Processing Tasks:");
            while (tasks.Count > 0)
            {
                string task = tasks.Dequeue();
                Console.WriteLine(task);
            }
        }
    }
}

Explanation:

  • We create a queue of strings.
  • Add elements to the queue using Enqueue.
  • Remove and process the elements using Dequeue.

4. Stack Collection

A Stack in C# is a Last-In-First-Out (LIFO) collection. The last element added is the first element to be removed.

Code Example:

// File: StackExample.cs
using System;
using System.Collections.Generic;

namespace CollectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a stack of integers
            Stack stack = new Stack();

            // Push elements onto the stack
            stack.Push(10);
            stack.Push(20);
            stack.Push(30);

            // Pop elements from the stack
            Console.WriteLine("Stack Elements:");
            while (stack.Count > 0)
            {
                int item = stack.Pop();
                Console.WriteLine(item);
            }
        }
    }
}

Explanation:

  • We create a stack of integers.
  • Add elements to the stack using Push.
  • Remove elements using Pop.

5. HashSet Collection

A HashSet stores unique elements and does not allow duplicates.

Code Example:

// File: HashSetExample.cs
using System;
using System.Collections.Generic;

namespace CollectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a HashSet of strings
            HashSet fruits = new HashSet();

            // Add elements to the HashSet
            fruits.Add("Apple");
            fruits.Add("Banana");
            fruits.Add("Cherry");
            fruits.Add("Apple");  // Duplicate, will not be added

            // Display elements
            Console.WriteLine("Fruits in HashSet:");
            foreach (var fruit in fruits)
            {
                Console.WriteLine(fruit);
            }
        }
    }
}

Explanation:

  • We create a HashSet of strings.
  • Add elements to the HashSet. Duplicate elements are ignored.
  • Use a foreach loop to print the elements.

Conclusion

C# collections provide a versatile and powerful way to store and manipulate data. In this tutorial, we covered several commonly used collections, including List, Dictionary, Queue, Stack, and HashSet, each with its own unique strengths and use cases.

By understanding the characteristics of these collections and knowing when to use them, you can write more efficient and effective code. Whether you're storing simple values or managing complex data, mastering collections is a critical step in becoming a proficient C# programmer.