Lesson 20 — .NET Collections
Collections
The .NET collections library provides List
CSHARP — List
using System.Collections.Generic;
var names = new List<string> { "Thandi", "Sipho", "Lerato" };
names.Add("Bongani");
names.Insert(1, "Zanele"); // insert at index 1
names.Remove("Sipho"); // remove by value
names.RemoveAt(0); // remove by index
Console.WriteLine($"Count: {names.Count}");
Console.WriteLine(string.Join(", ", names));
// Sorting:
names.Sort(); // alphabetical
Console.WriteLine(string.Join(", ", names));
// Contains and IndexOf:
Console.WriteLine(names.Contains("Lerato")); // True
Console.WriteLine(names.IndexOf("Lerato")); // depends on sort order
CSHARP — Dictionary and HashSet
var marks = new Dictionary<string, double> {
["Thandi"] = 74.5,
["Sipho"] = 81.0,
["Lerato"] = 68.0
};
Console.WriteLine(marks["Sipho"]); // 81.0
// Safe access:
if (marks.TryGetValue("Zanele", out double val))
Console.WriteLine(val);
else
Console.WriteLine("Key not found.");
// Iterate:
foreach (var (name, mark) in marks)
Console.WriteLine($"{name}: {mark:F1}%");
// HashSet — unique items:
var courses = new HashSet<string> { "Java", "C#", "SQL", "Java" }; // dup ignored
Console.WriteLine(courses.Count); // 3
courses.UnionWith(new[] { "Python", "C#" }); // adds Python, ignores C#
Practice Task
Your Turn
Build a CourseManager: List<Learner> for all learners, Dictionary<string, List<Learner>> mapping course to its learners, Enrol(Learner, course), GetAverage(course), TopLearner() returning the highest-mark learner. Test with 8 learners in 3 courses.
Common Mistakes
- d[key] throws KeyNotFoundException — always use TryGetValue for lookups that might fail.
- Modifying a List inside foreach — throws InvalidOperationException.
- Count property (not Length) for List/Dictionary.
- Dictionary doesn't guarantee insertion order (use SortedDictionary or LinkedHashMap equivalent for ordered).
Professional Tip
Collections are the backbone of nearly every application. A List to hold records, a Dictionary to look them up by key, a HashSet to deduplicate — these three cover the vast majority of real-world needs.
Mini Quiz
Which .NET collection stores unique items?
HashSet guarantees uniqueness — duplicates are silently ignored when added.