Data Structures in C#: Exploring Dictionaries

Data Structures in C#: Exploring Dictionaries

Welcome to our C# data structures revision! Today, we will delve deeply into C# Dictionaries. Much like a bookshelf, Dictionaries allow you to quickly select the book (value) you desire by reading its label (key). They are vital in C# for quickly accessing values using keys and for efficiently inserting and deleting keys. So, let's explore C# Dictionaries for a clearer understanding of these concepts.

Introduction to C# Dictionaries and Operations

Before diving into real-world applications, it’s essential to grasp the fundamentals of C# Dictionaries, a crucial data structure for storing data as key-value pairs. Understanding how to define and perform basic operations on them prepares us for more complex implementations.

In C#, keys in a Dictionary must be unique and immutable. Common types used as keys include strings, integers, enums, and any object that overrides the GetHashCode() and Equals() methods. This ensures the keys are suitable for fast lookups.

using System;
using System.Collections.Generic;

// Defining a Dictionary
Dictionary<string, int> ageDictionary = new Dictionary<string, int>();

// Adding entries
ageDictionary["Alice"] = 25;
ageDictionary["Bob"] = 30;
Console.WriteLine("After adding: ");
foreach (var entry in ageDictionary)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

// Updating entries
ageDictionary["Alice"] = 26; // Updates Alice's age
Console.WriteLine("\nAfter updating: ");
foreach (var entry in ageDictionary)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

// Retrieving values
int ageOfAlice = ageDictionary.ContainsKey("Alice") ? ageDictionary["Alice"] : -1;
Console.WriteLine($"\nAlice's Age: {ageOfAlice}");

// Removing entries
ageDictionary.Remove("Bob");
Console.WriteLine("\nAfter removing Bob: ");
foreach (var entry in ageDictionary)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

// Counting entries
int entryCount = ageDictionary.Count;
Console.WriteLine($"\nNumber of Entries: {entryCount}");
  • Defining a Dictionary: Use Dictionary<TKey, TValue> where TKey is the type for keys and TValue is the type for values.
  • Adding: Initial addition of entries, printed after insertion.
  • Updating: Demonstrates updating the existing entry by reassigning Alice's age.
  • Retrieving: Uses ContainsKey to check existence and retrieve values.
  • Removing: Uses the Remove method to delete entries.
  • Counting: Uses the Count property to get the number of entries.

Now that you're familiar with these operations, let's apply them in a PhoneBook class.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal