Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Generic Dictionary Implementation in C#

Tech May 8 3

The Dictionary<TKey, TValue> class in the System.Collections.Generic namespace is a powerful collection designed for high-performance data retrieval using keys. It maps unique keys to specific values, providing an average time complexity of O(1) for lookups.

Core Characteristics

  • Namespace: Requires System.Collections.Generic.
  • Uniqueness: Every key within a dictionary must be unique; however, values can be duplicated.
  • Type Safety: Both keys and values are strongly typed, supporting any data type from primitives like int to complex custom objects.
  • Ordering: The collection does not guarantee a specific sort order for its elements.

Basic Usage

Initializing a dictionary and populating it with data is straightforward. Use the Add method or the collection initializer syntax.

// Creating a dictionary to map file extensions to application names
var appRegistry = new Dictionary<string, string>();

// Inserting elements
appRegistry.Add(".txt", "Notepad");
appRegistry.Add(".jpg", "Photos App");
appRegistry.Add(".pdf", "Adobe Reader");

Data Access and Modification

You can retrieve or update values using the indexer property. If the key exists, assigning a value to that key updates it; otherwise, it creates a new entry.

// Reading a value
string reader = appRegistry[".pdf"];
Console.WriteLine($"Handler: {reader}");

// Modifying a value
appRegistry[".pdf"] = "Edge Browser";

Iteration Techniques

You can iterate over keys, values, or the entire key-value pair collection.

// Iterating through Keys
foreach (string ext in appRegistry.Keys)
{
    Console.WriteLine($"Extension: {ext}");
}

// Iterating through Values
foreach (string app in appRegistry.Values)
{
    Console.WriteLine($"Application: {app}");
}

// Iterating through KeyValuePair objects
foreach (KeyValuePair<string, string> entry in appRegistry)
{
    Console.WriteLine($"{entry.Key} is opened by {entry.Value}");
}

Safe Key Handling

Attempting to add a duplicate key or accessing a non-existent key via the indexer will throw an exception. Use ContainsKey or TryGetValue to perform safe operations.

// Preventing duplicate key errors
if (!appRegistry.ContainsKey(".txt"))
{
    appRegistry.Add(".txt", "TextEdit");
}

// Using TryGetValue for safe retrieval
if (appRegistry.TryGetValue(".png", out string handler))
{
    Console.WriteLine($"Found: {handler}");
}
else
{
    Console.WriteLine("Extension not registered.");
}

// Removing an entry
appRegistry.Remove(".jpg");

Working with Custom Objects

Dictionaries are frequently used to store complex data structures indexed by a unique identifier.

public class UserProfile
{
    public int Id { get; set; }
    public string Username { get; set; }
}

// Mapping User IDs to UserProfile objects
var users = new Dictionary<int, UserProfile>();

for (int i = 1; i <= 3; i++)
{
    users.Add(i, new UserProfile { Id = i * 10, Username = $"User_{i}" });
}

foreach (var entry in users)
{
    Console.WriteLine($"ID: {entry.Key}, Name: {entry.Value.Username}");
}

Essential Properties and Methods

Member Description
Count Returns the total number of key/value pairs.
Keys Returns a collection containing all keys.
Values Returns a collection containing all values.
Add(K, V) Inserts a new entry; throws if the key exists.
Clear() Removes all entries from the dictionary.
ContainsKey(K) Checks if a specific key exists in the collection.
ContainsValue(V) Checks if a specific value exists in the collection.
Remove(K) Removes the entry associated with the specified key.
TryGetValue(K, out V) Safely retrieves a value without throwing an exception.
Tags: C#.NET

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.