17. Collections in C#
Level: Beginner
- 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.
| Collection | Use |
|---|---|
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
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:
- Add 5 more students to the list
- Print total using
Count - Create
Dictionary<int, string>for roll->name lookup - Find a student by roll number using
TryGetValue - Create
HashSet<int>for submitted assignment IDs, add duplicates (should ignore)
See collections managing many objects easily.
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
- Use
List<T>for normal lists. - Use
Dictionary<TKey,TValue>for lookup by key. - Use
HashSet<T>for unique values. - Use
Queue<T>for first-come-first-served work. - Use
Stack<T>for undo/back behavior. - 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
| Question | Answer |
|---|---|
| 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> |
A collection stores multiple values together, such as many students or many marks.
Array has fixed size. List<T> can grow and shrink.
Use Dictionary when you need fast lookup by a key, like roll number or subject name.
It safely checks whether a key exists and avoids a crash if the key is missing.
Use HashSet when duplicate values should not be stored.
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.
C# Section Links
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.