Skip to content

sametyilmaztemel/csharp-data-structures

Repository files navigation

C# Data Structures 📚

.NET Language License Topics

A comprehensive, example-driven guide to C#'s built-in generic collection data structures. Each file is a self-contained, runnable console application demonstrating real-world usage patterns, best practices, and performance characteristics.


📑 Table of Contents


Overview

This repository provides practical, well-commented C# examples for seven essential data structures available in the System.Collections.Generic namespace. Each example is designed to be:

  • Self-contained — single file, no external dependencies
  • Runnable — copy into a console project and execute
  • Educational — extensive comments explaining every operation
  • Practical — real-world scenarios (phone books, travel routes, book indexes)

Data Structures Covered

# Data Structure File Key Concept
1 Dictionary<TKey, TValue> 01_Dictionary.cs Key-value lookups
2 HashSet<T> 02_HashSet.cs Unique elements & set algebra
3 LinkedList<T> 03_LinkedList.cs Doubly-linked node navigation
4 Queue<T> 04_Queue.cs FIFO processing
5 SortedDictionary<TKey, TValue> 05_SortedDictionary.cs Sorted key-value pairs
6 SortedSet<T> 06_SortedSet.cs Sorted unique elements
7 Stack<T> 07_Stack.cs LIFO processing

Complexity Analysis

Data Structure Add / Insert Remove Lookup / Contains Enumeration Internal Structure
Dictionary<K,V> O(1) avg O(1) avg O(1) avg O(n) Hash table
HashSet<T> O(1) avg O(1) avg O(1) avg O(n) Hash table
LinkedList<T> O(1)¹ O(1)² O(n) O(n) Doubly-linked list
Queue<T> O(1) O(1)³ O(n) O(n) Circular array
SortedDictionary<K,V> O(log n) O(log n) O(log n) O(n) Red-black tree
SortedSet<T> O(log n) O(log n) O(log n) O(n) Red-black tree
Stack<T> O(1) O(1)³ O(n) O(n) Dynamic array

¹ AddFirst/AddLast/AddBefore/AddAfter (given a node reference) ² Remove(node) — Remove(value) is O(n)
³ Dequeue/Pop from front/top only

Notes:

  • Average case for hash-based structures; worst case is O(n) due to hash collisions.
  • Sorted structures use balanced BST (red-black tree), guaranteeing O(log n) worst case.
  • Queue<T> and Stack<T> may occasionally need O(n) for internal array resizing.

Getting Started

Prerequisites

Quick Start

# Clone the repository
git clone https://github.com/sametyilmaztemel/csharp-data-structures.git
cd csharp-data-structures

# Create a console project
dotnet new console -n DataStructuresDemo

# Copy any example file as Program.cs
cp 01_Dictionary.cs DataStructuresDemo/Program.cs

# Run it
cd DataStructuresDemo
dotnet run

Alternative — Run directly with script-style

# Using dotnet-script (global tool)
dotnet tool install -g dotnet-script
dotnet script 01_Dictionary.cs

File Index

csharp-data-structures/
├── 01_Dictionary.cs         # Key-value pairs: phone codes, employee directory
├── 02_HashSet.cs            # Set operations: vowels, duplicates removal
├── 03_LinkedList.cs         # Node navigation: travel route planner
├── 04_Queue.cs              # FIFO processing: task scheduler, vowel queue
├── 05_SortedDictionary.cs   # Sorted key-value: book index
├── 06_SortedSet.cs          # Sorted unique set: mathematical set operations
├── 07_Stack.cs              # LIFO processing: digit decomposition, ASCII stack
└── README.md                # This file

Detailed Examples

1. Dictionary

File: 01_Dictionary.cs

Demonstrates Dictionary<TKey, TValue> with a city phone code lookup and an employee directory using a custom Employee class.

var phoneCodes = new Dictionary<int, string>
{
    { 212, "New York" },
    { 415, "San Francisco" },
    { 202, "Washington D.C." }
};

// O(1) average lookup
if (phoneCodes.TryGetValue(212, out string city))
    Console.WriteLine($"Area 212 → {city}");  // New York

// Custom object values
var employees = new Dictionary<int, Employee>();
employees.Add(1001, new Employee(1001, "Alice Johnson", "Engineering"));

Key operations covered: Add, Remove, ContainsKey, ContainsValue, TryGetValue, TryAdd, foreach iteration, Keys/Values properties.


2. HashSet

File: 02_HashSet.cs

Demonstrates HashSet<T> with English vowel characters and set algebra operations.

var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };

// Set operations
var setA = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
var setB = new HashSet<char> { 'i', 'o', 'u', 'x', 'y' };

setA.UnionWith(setB);               // { a, e, i, o, u, x, y }
setA.IntersectWith(setB);           // { i, o, u }
setA.SymmetricExceptWith(setB);     // { a, e, x, y }

Key operations covered: Add, Remove, UnionWith, IntersectWith, ExceptWith, SymmetricExceptWith, IsSubsetOf, Overlaps, duplicate removal from lists.


3. LinkedList

File: 03_LinkedList.cs

Demonstrates LinkedList<T> by building a multi-city travel route with insertions at various positions.

var route = new LinkedList<string>();
route.AddLast("London");
route.AddLast("Paris");
route.AddFirst("Edinburgh");       // Edinburgh → London → Paris

LinkedListNode<string> paris = route.Find("Paris");
route.AddAfter(paris, "Barcelona"); // Insert after Paris
route.AddBefore(paris, "Zurich");   // Insert before Paris

// Navigate forward
var node = route.First;
while (node != null)
{
    Console.WriteLine(node.Value);
    node = node.Next;
}

Key operations covered: AddFirst, AddLast, AddAfter, AddBefore, Find, FindLast, Remove, RemoveFirst, RemoveLast, forward/backward traversal via Next/Previous.


4. Queue

File: 04_Queue.cs

Demonstrates Queue<T> with a task scheduling example and an interactive vowel processing pipeline.

var tasks = new Queue<string>();
tasks.Enqueue("Download files");
tasks.Enqueue("Parse data");
tasks.Enqueue("Generate report");

string next = tasks.Dequeue(); // "Download files" (FIFO)
string peek  = tasks.Peek();   // "Parse data" (no removal)

Key operations covered: Enqueue, Dequeue, Peek, Count, ToArray, safe dequeue pattern.


5. SortedDictionary

File: 05_SortedDictionary.cs

Demonstrates SortedDictionary<TKey, TValue> with a book index where letters map to topic lists.

var bookIndex = new SortedDictionary<char, List<string>>();
bookIndex.Add('C', new List<string> { "Collections", "Concurrency" });
bookIndex.Add('A', new List<string> { "Arrays", "Async" });
bookIndex.Add('E', new List<string> { "Exceptions", "Events" });

// Keys are auto-sorted: A, C, E
foreach (var entry in bookIndex)
{
    Console.WriteLine($"[{entry.Key}] {string.Join(", ", entry.Value)}");
}

Key operations covered: Add, Remove, TryGetValue, ContainsKey, nested List<T> iteration, sorted key enumeration, Keys.First()/Keys.Last().


6. SortedSet

File: 06_SortedSet.cs

Demonstrates SortedSet<T> with mathematical set operations, unique element extraction, and range queries.

var setA = new SortedSet<int> { 1, 2, 3, 4, 5 };
var setB = new SortedSet<int> { 3, 4, 5, 6, 7 };

setA.UnionWith(setB);               // { 1, 2, 3, 4, 5, 6, 7 }
setA.IntersectWith(setB);           // { 3, 4, 5 }
setA.SymmetricExceptWith(setB);     // { 1, 2, 6, 7 }

// Range queries
var data = new SortedSet<int> { 5, 10, 15, 20, 25, 30 };
var range = data.GetViewBetween(10, 25); // { 10, 15, 20, 25 }

Key operations covered: Add, Remove, Min, Max, UnionWith, IntersectWith, SymmetricExceptWith, ExceptWith, GetViewBetween, IsSubsetOf, duplicate extraction from random data.


7. Stack

File: 07_Stack.cs

Demonstrates Stack<T> with digit decomposition, ASCII character processing, and basic push/pop patterns.

// Digit decomposition
int number = 12345;
var stack = new Stack<int>();
while (number > 0)
{
    stack.Push(number % 10);  // Push each digit
    number /= 10;
}
// Pop reveals digits in reverse order: 1, 2, 3, 4, 5

// Basic usage
var s = new Stack<string>();
s.Push("First");
s.Push("Second");
string top = s.Pop();  // "Second" (LIFO)

Key operations covered: Push, Pop, Peek, Count, Contains, ToArray, number reversal via stack.


When to Use What

Scenario Recommended Structure Why
Fast key-based lookup Dictionary<K,V> O(1) average lookup by key
Remove duplicates HashSet<T> O(1) average add, auto-dedup
Frequent insertions in middle LinkedList<T> O(1) insert with node reference
Task/job processing (FIFO) Queue<T> Natural first-in-first-out order
Ordered key-value pairs SortedDictionary<K,V> Keys always sorted, O(log n) ops
Sorted unique elements SortedSet<T> Auto-sorted, range queries
Undo / backtracking (LIFO) Stack<T> Natural last-in-first-out order
Priority ordering SortedSet<T> Maintains order on insert
Set math (union, intersect) HashSet<T> or SortedSet<T> Built-in set operations

Contributing

Contributions are welcome! Feel free to:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/new-example)
  3. Commit your changes (git commit -m 'Add new example')
  4. Push to the branch (git push origin feature/new-example)
  5. Open a Pull Request

License

This project is licensed under the MIT License — see the LICENSE file for details.


Built with ❤️ using C# and .NET

About

A comprehensive C# collection demonstrating core data structures with practical examples and complexity analysis

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages