In C#, collections are used to store, manage, and manipulate groups of related objects. Collections provide a more flexible way to work with groups of objects compared to arrays. This module will cover the different types of collections available in C#, their usage, and practical examples.

Key Concepts

  1. Types of Collections:

    • ArrayList
    • List
    • Dictionary<TKey, TValue>
    • Queue
    • Stack
    • HashSet
  2. Generic vs Non-Generic Collections:

    • Generic collections provide type safety and better performance.
    • Non-generic collections can store any type of object but lack type safety.
  3. Common Operations:

    • Adding elements
    • Removing elements
    • Accessing elements
    • Iterating through collections

Types of Collections

ArrayList

The ArrayList class is a non-generic collection that can store any type of object.

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList arrayList = new ArrayList();
        arrayList.Add(1);
        arrayList.Add("Hello");
        arrayList.Add(3.14);

        foreach (var item in arrayList)
        {
            Console.WriteLine(item);
        }
    }
}

List

The List<T> class is a generic collection that provides type safety and better performance.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> intList = new List<int>();
        intList.Add(1);
        intList.Add(2);
        intList.Add(3);

        foreach (int item in intList)
        {
            Console.WriteLine(item);
        }
    }
}

Dictionary<TKey, TValue>

The Dictionary<TKey, TValue> class is a generic collection that stores key-value pairs.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        dictionary["one"] = 1;
        dictionary["two"] = 2;
        dictionary["three"] = 3;

        foreach (var kvp in dictionary)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}

Queue

The Queue<T> class represents a first-in, first-out (FIFO) collection of objects.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Queue<string> queue = new Queue<string>();
        queue.Enqueue("First");
        queue.Enqueue("Second");
        queue.Enqueue("Third");

        while (queue.Count > 0)
        {
            Console.WriteLine(queue.Dequeue());
        }
    }
}

Stack

The Stack<T> class represents a last-in, first-out (LIFO) collection of objects.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Stack<string> stack = new Stack<string>();
        stack.Push("First");
        stack.Push("Second");
        stack.Push("Third");

        while (stack.Count > 0)
        {
            Console.WriteLine(stack.Pop());
        }
    }
}

HashSet

The HashSet<T> class provides high-performance set operations.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> hashSet = new HashSet<int>();
        hashSet.Add(1);
        hashSet.Add(2);
        hashSet.Add(3);
        hashSet.Add(1); // Duplicate, will not be added

        foreach (int item in hashSet)
        {
            Console.WriteLine(item);
        }
    }
}

Practical Exercises

Exercise 1: Working with List

Task: Create a List<string> to store names. Add five names to the list, remove one, and then print all the names.

Solution:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> names = new List<string> { "Alice", "Bob", "Charlie", "David", "Eve" };
        names.Remove("Charlie");

        foreach (string name in names)
        {
            Console.WriteLine(name);
        }
    }
}

Exercise 2: Using Dictionary<TKey, TValue>

Task: Create a Dictionary<string, int> to store the names and ages of five people. Print each name and age.

Solution:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> people = new Dictionary<string, int>
        {
            { "Alice", 30 },
            { "Bob", 25 },
            { "Charlie", 35 },
            { "David", 40 },
            { "Eve", 28 }
        };

        foreach (var person in people)
        {
            Console.WriteLine($"Name: {person.Key}, Age: {person.Value}");
        }
    }
}

Common Mistakes and Tips

  • Type Safety: Always prefer generic collections (List<T>, Dictionary<TKey, TValue>, etc.) over non-generic collections (ArrayList, Hashtable) for type safety and performance.
  • Null Values: Be cautious when adding or accessing elements in collections that can store null values.
  • Iteration: Use foreach loops for iterating through collections to avoid index-related errors.

Conclusion

In this section, we explored various types of collections in C#, including ArrayList, List<T>, Dictionary<TKey, TValue>, Queue<T>, Stack<T>, and HashSet<T>. We discussed their usage, provided practical examples, and highlighted common operations. Understanding collections is crucial for efficient data management and manipulation in C#. In the next module, we will delve into LINQ (Language Integrated Query) to further enhance our data handling capabilities.

© Copyright 2024. All rights reserved