Master C# Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Collections in C#

Collections in C# are used to store, organize, and manipulate groups of objects. Collections provide flexible ways to work with multiple values and are widely used in real-world .NET applications.

Simple Definition: A collection is a container that can store multiple values or objects and provides methods to add, remove, search, and manage those values.

Why Do We Use Collections?

Collections are useful when the number of elements may change during program execution or when we need specific ways to organize and access data.

  • Store multiple values in a single object.
  • Add and remove elements dynamically.
  • Search and sort data easily.
  • Store data in key-value pairs.
  • Manage unique values.
  • Implement FIFO and LIFO data structures.

Types of Collections in C#

Collection Purpose
List<T> Stores an ordered collection of elements
Dictionary<TKey,TValue> Stores data using key-value pairs
HashSet<T> Stores unique elements
Queue<T> Stores elements using FIFO order
Stack<T> Stores elements using LIFO order

1. List<T>

List<T> is a generic collection used to store an ordered collection of strongly typed elements. Unlike arrays, a List can dynamically grow or shrink as elements are added or removed.

Creating a List

C#
using System;
 
List numbers = new List();

numbers.Add(10);
numbers.Add(20);
numbers.Add(30);

foreach (int number in numbers)
{
    Console.WriteLine(number);
}
Output
10
20
30

Adding Elements to a List

The Add() method is used to add a new element to the end of a List.

C#
using System;
 
List students = new List();

students.Add("Rahul");
students.Add("Sneha");
students.Add("Amit");

Console.WriteLine(students.Count);
Output
3

Accessing List Elements

C#
using System;
 
List students =
    new List { "Rahul", "Sneha", "Amit" };

Console.WriteLine(students[0]);
Console.WriteLine(students[2]);
Output
Rahul
Amit

Removing Elements from a List

The Remove() method removes a specific value from a List.

C#
using System;
 
List numbers =
    new List { 10, 20, 30, 40 };

numbers.Remove(30);

foreach (int number in numbers)
{
    Console.WriteLine(number);
}
Output
10
20
40

List Count

The Count property returns the number of elements currently stored in the List.

C#
using System;
 
List numbers =
    new List { 10, 20, 30, 40, 50 };

Console.WriteLine(numbers.Count);
Output
5

Sorting a List

C#
using System;
 
List numbers =
    new List { 50, 10, 40, 20, 30 };

numbers.Sort();

foreach (int number in numbers)
{
    Console.WriteLine(number);
}
Output
10
20
30
40
50

2. Dictionary<TKey, TValue>

A Dictionary stores data in key-value pairs. Each key must be unique and is used to access its corresponding value.

Creating a Dictionary

C#
using System;
 
Dictionary students =
    new Dictionary();

students.Add(101, "Rahul");
students.Add(102, "Sneha");
students.Add(103, "Amit");

Console.WriteLine(students[102]);
Output
Sneha

Checking a Dictionary Key

The ContainsKey() method checks whether a specified key exists in the Dictionary.

C#
using System;
 
Dictionary students =
    new Dictionary();

students.Add(101, "Rahul");
students.Add(102, "Sneha");

if (students.ContainsKey(101))
{
    Console.WriteLine("Student Found");
}
Output
Student Found

Iterating Through a Dictionary

C#
using System;
 
Dictionary students =
    new Dictionary();

students.Add(101, "Rahul");
students.Add(102, "Sneha");
students.Add(103, "Amit");

foreach (KeyValuePair student in students)
{
    Console.WriteLine(
        student.Key + " - " + student.Value);
}
Output
101 - Rahul
102 - Sneha
103 - Amit

3. HashSet<T>

HashSet<T> stores unique elements. If we try to add the same value more than once, the duplicate value is ignored.

Creating a HashSet

C#
using System;
 
HashSet numbers = new HashSet();

numbers.Add(10);
numbers.Add(20);
numbers.Add(10);
numbers.Add(30);

foreach (int number in numbers)
{
    Console.WriteLine(number);
}
Output
10
20
30
Important: HashSet does not store duplicate values.

Checking an Element in HashSet

C#
using System;
 
HashSet courses =
    new HashSet();

courses.Add("C#");
courses.Add(".NET");
courses.Add("Python");

Console.WriteLine(courses.Contains("C#"));
Output
True

4. Queue<T>

Queue<T> follows the FIFO principle: First In, First Out. The element added first is removed first.

Real-World Example: A customer queue at a bank follows the FIFO principle. The customer who arrives first is served first.

Creating a Queue

C#
using System;
 
Queue customers =
    new Queue();

customers.Enqueue("Rahul");
customers.Enqueue("Sneha");
customers.Enqueue("Amit");

Console.WriteLine(customers.Dequeue());
Output
Rahul

Enqueue() and Dequeue()

Enqueue() adds an element to the end of the Queue. Dequeue() removes the element from the beginning.

C#
using System;
 
Queue numbers = new Queue();

numbers.Enqueue(10);
numbers.Enqueue(20);
numbers.Enqueue(30);

Console.WriteLine(numbers.Dequeue());
Console.WriteLine(numbers.Dequeue());
Output
10
20

5. Stack<T>

Stack<T> follows the LIFO principle: Last In, First Out. The element added last is removed first.

Real-World Example: A stack of plates follows the LIFO principle. The last plate placed on the stack is the first plate removed.

Creating a Stack

C#
using System;
 Stack numbers = new Stack();

numbers.Push(10);
numbers.Push(20);
numbers.Push(30);

Console.WriteLine(numbers.Pop());
Output
30

Push() and Pop()

Push() adds an element to the Stack. Pop() removes and returns the top element.

C#
using System;
 
Stack pages =
    new Stack();

pages.Push("Home");
pages.Push("Products");
pages.Push("Contact");

Console.WriteLine(pages.Pop());
Console.WriteLine(pages.Pop());
Output
Contact
Products

Queue vs Stack

Feature Queue Stack
Principle FIFO LIFO
Add Method Enqueue() Push()
Remove Method Dequeue() Pop()
First Removed First Added Last Added
Example Customer Queue Browser History

Collection Comparison

Collection Stores Duplicates Access
List<T> Ordered elements Allowed Index
Dictionary<TKey,TValue> Key-value pairs Keys must be unique Key
HashSet<T> Unique elements Not allowed Value
Queue<T> Ordered elements Allowed FIFO
Stack<T> Ordered elements Allowed LIFO

Applications 👨‍🏫📩

  • List<T>: Student lists, product lists, employee records.
  • Dictionary<TKey,TValue>: Student ID and student name mapping.
  • HashSet<T>: Unique user IDs, tags, categories.
  • Queue<T>: Customer queues, print jobs, background tasks.
  • Stack<T>: Browser history, undo operations, navigation history.
CIIT Practical Point: Collections are used extensively in ASP.NET Core applications, Web APIs, database operations, business logic, service layers, reporting systems and enterprise applications.

Common Mistakes with Collections

  • Choose the collection based on the requirement.
  • Use List when indexed and dynamically sized data is required.
  • Use Dictionary when data needs to be accessed using a key.
  • Use HashSet when duplicate values should not be stored.
  • Remember that Queue follows FIFO.
  • Remember that Stack follows LIFO.
  • Do not access a List using an invalid index.
  • Do not add duplicate keys to a Dictionary.

Interview Questions

1. What is a Collection in C#?

A collection is an object used to store and manage multiple elements.

2. What is the difference between Array and List?

An array has a fixed size, while a List can dynamically grow or shrink.

3. What is a Dictionary?

A Dictionary stores data in key-value pairs.

4. What is HashSet?

HashSet is a collection that stores unique elements and does not allow duplicate values.

5. What is FIFO?

FIFO means First In, First Out. Queue follows this principle.

6. What is LIFO?

LIFO means Last In, First Out. Stack follows this principle.

7. Which collection is used for key-value pairs?

Dictionary<TKey,TValue> is used for key-value pairs.

Collections Summary

  • Collections are used to store and manage multiple elements.
  • List<T> provides a dynamically sized ordered collection.
  • Dictionary<TKey,TValue> stores key-value pairs.
  • HashSet<T> stores unique values.
  • Queue<T> follows FIFO.
  • Stack<T> follows LIFO.
  • Collections provide useful methods for adding, removing, searching and sorting data.
  • Generic collections provide strong type safety.
  • Collections are widely used in real-world .NET applications.

Practice Questions

  1. Create a List<int> and add five numbers.
  2. Remove an element from a List.
  3. Sort a List in ascending order.
  4. Create a Dictionary containing student ID and student name.
  5. Search for a key in a Dictionary using ContainsKey().
  6. Create a HashSet and add duplicate values.
  7. Check whether a value exists in a HashSet.
  8. Create a Queue and demonstrate Enqueue() and Dequeue().
  9. Create a Stack and demonstrate Push() and Pop().
  10. Explain the difference between Queue and Stack.
  11. Choose the appropriate collection for a given real-world scenario.
  12. Compare List, Dictionary, HashSet, Queue and Stack.