C# Collections

List, Dictionary and HashSet.

✍️ 2 exercises in this lesson

System.Collections.Generic provides type-safe collections:

  • List<T>: Add(), Remove(), Count, Sort(), Contains()
  • Dictionary<TKey, TValue>: key → value; TryGetValue(), ContainsKey()
  • HashSet<T>: unique values
  • Queue<T> and Stack<T>

Key Takeaways: C# Collections

Mastering C# Collections helps you write clean and reliable C# code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C# Collections Code Example

C#
var cities = new List<string> { "Lahore", "Karachi" };
cities.Add("Quetta");
cities.Remove("Karachi");
cities.Sort();
Console.WriteLine(string.Join(", ", cities) + $" ({cities.Count})");

var stock = new Dictionary<string, int> { ["Laptop"] = 12, ["Mouse"] = 150 };
stock["Monitor"] = 25;
if (stock.TryGetValue("Mouse", out int qty)) Console.WriteLine($"Mouse: {qty}");

var tags = new HashSet<string> { "csharp", "dotnet", "csharp" };
Console.WriteLine(tags.Count);
Output
Lahore, Quetta (2)
Mouse: 150
2
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C# Collections Practice Exercises

Check what you learned in “C# Collections”.

/ 2 solved
Fill in the blank

Create a list of strings.

var cities = new <string>();
✓ Correct! Not quite. Try again.
Multiple choice

Which collection stores key-value pairs?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services