Skip to main content

17. Collections in C#

Level: Beginner

ℹ️ What You'll Learn
  • What collections are
  • Why collections are better than many separate variables
  • Use List<T> for many students
  • Use Dictionary<TKey,TValue> for fast lookup
  • Use HashSet<T> for unique values
  • Understand Queue and Stack at a beginner level

Collections store many values together.

In a School Management System, we need collections for:

  • Many students
  • Many marks
  • Many subjects
  • Student lookup by roll number
  • Unique submitted assignment IDs

The Problem: Too Many Separate Objects

Without collection:

string student1 = "Sahasra";
string student2 = "Priya";
string student3 = "Arjun";

This is not practical for 40 students.

Better:

List<string> students = new List<string>();
students.Add("Sahasra");
students.Add("Priya");
students.Add("Arjun");

Quick Definitions

  • Collection - Object storing multiple values
  • List - Ordered collection that grows/shrinks
  • Dictionary - Collection finding values by key (key-value pairs)
  • HashSet - Collection storing unique values only
  • Queue - First in, first out (FIFO) collection
  • Stack - Last in, first out (LIFO) collection
  • Generic - Collection type like List<T> where T can be any type
  • Key - Label to find value in Dictionary
  • Value - Data stored in Dictionary at a key
  • Enumerate - Loop through all items in collection

What is a Collection?

A collection is an object that stores multiple values.

CollectionUse
List<T>Ordered list of items
Dictionary<TKey,TValue>Find value by key
HashSet<T>Store unique values only
Queue<T>First in, first out
Stack<T>Last in, first out

List Collection

Use List<T> when you want a growing list.

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

students.Add("Sahasra");
students.Add("Priya");
students.Add("Arjun");

foreach (string student in students)
{
Console.WriteLine(student);
}

Useful operations:

students.Count;
students[0];
students.Remove("Sahasra");
students.Contains("Priya");

List of Student Objects

List<Student> students = new List<Student>();

students.Add(new Student { Name = "Sahasra", ClassName = "10-A", Percentage = 84.8 });
students.Add(new Student { Name = "Priya", ClassName = "10-A", Percentage = 91.2 });

foreach (Student student in students)
{
Console.WriteLine($"{student.Name} - {student.Percentage}");
}

public class Student
{
public string Name { get; set; } = "";
public string ClassName { get; set; } = "";
public double Percentage { get; set; }
}

Dictionary Collection

Use Dictionary when you want to find something quickly by a key.

Example: subject marks.

Dictionary<string, int> marks = new Dictionary<string, int>();

marks["Maths"] = 91;
marks["Science"] = 85;
marks["English"] = 78;

Console.WriteLine(marks["Maths"]);

Safe lookup:

if (marks.TryGetValue("Physics", out int physicsMarks))
{
Console.WriteLine(physicsMarks);
}
else
{
Console.WriteLine("Physics marks not found.");
}

HashSet Collection

Use HashSet<T> when values must be unique.

HashSet<int> submittedAssignments = new HashSet<int>();

submittedAssignments.Add(101);
submittedAssignments.Add(102);
submittedAssignments.Add(101);

Console.WriteLine(submittedAssignments.Count); // 2

Duplicate 101 is ignored.

Queue Collection

Queue means first in, first out.

Example: fee counter queue.

Queue<string> queue = new Queue<string>();

queue.Enqueue("Sahasra");
queue.Enqueue("Priya");
queue.Enqueue("Arjun");

Console.WriteLine(queue.Dequeue()); // Sahasra
Console.WriteLine(queue.Dequeue()); // Priya

Stack Collection

Stack means last in, first out.

Example: undo actions.

Stack<string> actions = new Stack<string>();

actions.Push("Added Sahasra");
actions.Push("Updated Priya");
actions.Push("Deleted Arjun");

Console.WriteLine(actions.Pop()); // Deleted Arjun

Full Example: Student List

💻 Try It — Console App
💡 Paste into Program.cs and press F5⌥ GitHub
List<Student> students = new List<Student>();

students.Add(new Student { RollNumber = 101, Name = "Sahasra", ClassName = "10-A", Percentage = 84.8 });
students.Add(new Student { RollNumber = 102, Name = "Priya", ClassName = "10-A", Percentage = 91.2 });
students.Add(new Student { RollNumber = 103, Name = "Arjun", ClassName = "10-B", Percentage = 62.5 });

Console.WriteLine("=== Students ===");

foreach (Student student in students)
{
Console.WriteLine($"{student.RollNumber} - {student.Name} - {student.ClassName} - {student.Percentage}");
}

Console.WriteLine($"Total Students: {students.Count}");

public class Student
{
public int RollNumber { get; set; }
public string Name { get; set; } = "";
public string ClassName { get; set; } = "";
public double Percentage { get; set; }
}

When You'll Use This in SMS

List is everywhere in SMS.

List<Student> students; // All students in school
List<Teacher> teachers; // All teachers
List<Subject> subjects; // All subjects offered
List<Exam> exams; // All exams this year
List<ExamResult> results; // All marks entered

Dictionary for fast lookup.

Dictionary<int, Student> rollToStudent; // Find by roll number
Dictionary<string, int> subjectToMaxMarks; // Find max marks by subject
Dictionary<int, FeeAccount> studentToFeeAccount; // Find fee by student

HashSet for unique IDs.

HashSet<int> submittedAssignments; // Students who submitted (no duplicates)
HashSet<string> enrolledSubjects; // Subjects taken (no repeats)

Queue for fair service.

Queue<string> feeCounterQueue; // Students waiting to pay (first come, first served)

Stack for undo/back.

Stack<string> actionHistory; // Undo last action: delete, add, update

Real impact: Production SMS manages 1000+ students. Lists organize them, Dictionaries find them fast, HashSets prevent duplicates.


Try This Now

Run the student list example above. Then experiment:

  1. Add 5 more students to the list
  2. Print total using Count
  3. Create Dictionary<int, string> for roll->name lookup
  4. Find a student by roll number using TryGetValue
  5. Create HashSet<int> for submitted assignment IDs, add duplicates (should ignore)

See collections managing many objects easily.


ℹ️ Video Tutorial

Collections explained: List, Dictionary, HashSet, Queue, Stack with school examples. Video coming soon. Subscribe to NexCoding YouTube for updates.


Common Mistakes

Mistake 1: Using array when size changes

Use List<T> when students can be added/removed.

Mistake 2: Dictionary lookup without checking

Wrong:

int mark = marks["Physics"];

Better:

marks.TryGetValue("Physics", out int mark);

Mistake 3: Using List for unique values

Use HashSet<T> when duplicates should not be allowed.

Best Practices

  1. Use List<T> for normal lists.
  2. Use Dictionary<TKey,TValue> for lookup by key.
  3. Use HashSet<T> for unique values.
  4. Use Queue<T> for first-come-first-served work.
  5. Use Stack<T> for undo/back behavior.
  6. Use clear names like students, marksBySubject.

Practice Task

Create a List<string> of five subjects and print them using foreach.

Then create a Dictionary<string, int> for subject marks and print each subject with marks.

Quick Revision

QuestionAnswer
Which collection grows dynamically?List<T>
Which collection finds by key?Dictionary<TKey,TValue>
Which collection stores unique values?HashSet<T>
Which collection is FIFO?Queue<T>
Which collection is LIFO?Stack<T>

🎯 Q1: What is a collection?

A collection stores multiple values together, such as many students or many marks.

🎯 Q2: Difference between array and List?

Array has fixed size. List<T> can grow and shrink.

🎯 Q3: When should we use Dictionary?

Use Dictionary when you need fast lookup by a key, like roll number or subject name.

🎯 Q4: Why use TryGetValue?

It safely checks whether a key exists and avoids a crash if the key is missing.

🎯 Q5: When should we use HashSet?

Use HashSet when duplicate values should not be stored.


🤖Use AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

Use ChatGPT, Claude, or Copilot to go deeper on C# collections. Try these prompts:

  • "Explain List and Dictionary using school examples"
  • "Give me 5 practice tasks for C# collections"
  • "Explain HashSet, Queue, and Stack simply"
  • "Quiz me with 5 beginner questions about collections"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Use these links to continue the full Backend > C# topic from the top menu:

Target search terms for this lesson: c# collections, c# list tutorial, c# dictionary tutorial.


Next Article

LINQ - Querying Collections ->

nexcoding.in