🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C# Collections — Complete Beginner Guide

C# FundamentalsCollections🟢 Free Lesson

C# Collections — Complete Beginner Guide

Learning Objectives

  • Store key value pairs with Dictionary
  • Track unique items with HashSet
  • Process work in order with Queue
  • Manage last in data with Stack
  • Choose the right collection for the job

Why Collections Matter

Beyond arrays and lists, .NET offers specialized containers. Each optimizes a different access pattern: lookup by key, uniqueness, first-in processing, or last-in handling.

Most general purpose collections live in the Generic namespace. Include it once at the top of your file.

Dictionary

Dictionary maps unique keys to values. Lookups are fast compared with scanning a list.

Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Sam"] = 31;
ages["Nina"] = 28;

Console.WriteLine(ages["Sam"]);
Console.WriteLine(ages.Count);

Safe access

Indexing a missing key throws. Use TryGetValue or ContainsKey first.

Dictionary<string, string> caps = new Dictionary<string, string>();
caps["html"] = "Markup";

if (caps.TryGetValue("html", out string value))
{
    Console.WriteLine(value);
}

if (!caps.ContainsKey("css"))
{
    caps["css"] = "Styles";
}

Updating and removing

ages["Sam"] = 32;
ages.Remove("Nina");

foreach (KeyValuePair<string, int> kv in ages)
{
    Console.WriteLine(kv.Key + " is " + kv.Value);
}

Keys must be unique. Values may repeat.

HashSet

HashSet stores unique elements and focuses on set operations.

HashSet<string> tags = new HashSet<string>();
tags.Add("csharp");
tags.Add("dotnet");
tags.Add("csharp");

Console.WriteLine(tags.Count); // 2 unique entries

Set operations

HashSet<int> a = new HashSet<int> { 1, 2, 3 };
HashSet<int> b = new HashSet<int> { 3, 4 };

a.UnionWith(b);
Console.WriteLine(string.Join(", ", a));

HashSet<int> c = new HashSet<int> { 1, 2 };
HashSet<int> d = new HashSet<int> { 2, 3 };
c.IntersectWith(d);
Console.WriteLine(string.Join(", ", c));

Use HashSet when membership checks and uniqueness matter more than order.

Queue

Queue is first in, first out. Think of a line at a counter.

Queue<string> jobs = new Queue<string>();
jobs.Enqueue("Resize image");
jobs.Enqueue("Send email");
jobs.Enqueue("Generate report");

Console.WriteLine(jobs.Peek());
Console.WriteLine(jobs.Dequeue());
Console.WriteLine(jobs.Count);

Enqueue adds to the back. Peek looks at the front without removing. Dequeue removes from the front.

Stack

Stack is last in, first out. Think of a stack of plates.

Stack<string> pages = new Stack<string>();
pages.Push("Home");
pages.Push("Products");
pages.Push("Cart");

Console.WriteLine(pages.Peek());
Console.WriteLine(pages.Pop());
Console.WriteLine(pages.Count);

Push adds to the top. Peek reads the top. Pop removes the top.

Choosing a Collection

NeedCollection
Ordered growable itemsList
Key value lookupDictionary
Unique items or set mathHashSet
Process in arrival orderQueue
Undo or depth style flowStack
Fixed sized dataArray

Quick decision tips

  • Need indexes and sequence? Start with List
  • Need fast lookup by id? Use Dictionary
  • Need to drop duplicates? Use HashSet
  • Need fairness in processing? Use Queue
  • Need to reverse recent work? Use Stack

Iteration Patterns

Dictionary<string, int> stock = new Dictionary<string, int>
{
    ["pen"] = 10,
    ["bag"] = 4
};

foreach (KeyValuePair<string, int> item in stock)
{
    Console.WriteLine(item.Key + ": " + item.Value);
}

Queue<int> q = new Queue<int>(new[] { 1, 2, 3 });
while (q.Count > 0)
{
    Console.WriteLine(q.Dequeue());
}

Common Mistakes

Using list for frequent key lookups

Scanning a list for keys works in small demos but slows down as data grows. Prefer Dictionary for key based access.

Assuming HashSet order

Do not rely on HashSet enumeration order for business rules that need stable sequence. Use List or a sorted structure when order matters.

Forgetting TryGetValue

Direct indexing on missing keys throws KeyNotFoundException. Guard optional lookups.

Key Takeaways

💡

  • Dictionary provides unique key to value mapping with fast lookup
  • HashSet enforces uniqueness and supports set operations
  • Queue is first in first out; Stack is last in first out
  • Match the collection to the access pattern, not habit
  • Use TryGetValue for safe dictionary reads

Practice Questions

  1. Which collection should hold user ids mapped to profiles?
  2. How do you add and remove items from a Queue?
  3. What makes HashSet different from List when inserting duplicates?
  4. In what order does Stack pop elements compared with Queue dequeue?
  5. Build a small inventory Dictionary, print every key and value, and handle a missing key with TryGetValue.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C# Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement