dictionary in c# example

dictionary in c# example


Dictionary in C# Example

In C#, the Dictionary<TKey, TValue> class is a generic collection that stores key-value pairs. This collection is part of the System.Collections.Generic namespace and provides efficient access, insertion, and removal based on keys. This article provides an overview of dictionaries and practical examples of their usage.

Key Features of Dictionary<TKey, TValue>

  • Key-Value Pairs: Each key maps to a specific value.
  • Unique Keys: Each key in the dictionary must be unique.
  • Efficient Access: Fast lookup, insertion, and removal of elements using hash-based indexing.

Example: Creating and Using a Dictionary

Basic Operations

The following example demonstrates how to create a dictionary, add elements, access values, and iterate through its items:

 

using System;
using System.Collections.Generic;

public class DictionaryExample
{
    public static void Main()
    {
        // Create a dictionary with string keys and integer values
        Dictionary<string, int> scores = new Dictionary<string, int>();

        // Add elements to the dictionary
        scores.Add("Alice", 90);
        scores.Add("Bob", 85);
        scores.Add("Charlie", 95);

        // Access a value using the key
        int bobScore = scores["Bob"];
        Console.WriteLine($"Bob's score: {bobScore}");

        // Check if a key exists in the dictionary
        bool hasAlice = scores.ContainsKey("Alice");
        Console.WriteLine($"Does Alice have a score recorded? {hasAlice}");

        // Update an existing key-value pair
        scores["Charlie"] = 98;
        Console.WriteLine($"Charlie's updated score: {scores["Charlie"]}");

        // Remove an element by key
        scores.Remove("Bob");

        // Iterate through the dictionary using foreach
        Console.WriteLine("\nAll scores in the dictionary:");
        foreach (KeyValuePair<string, int> kvp in scores)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

Common Dictionary Operations

  • Add: Inserts a new key-value pair (Add(key, value)).
  • Remove: Deletes an element by key (Remove(key)).
  • ContainsKey: Checks if a key exists (ContainsKey(key)).
  • TryGetValue: Safely retrieves a value without exceptions (TryGetValue(key, out value)).
  • Count: Returns the number of key-value pairs.

Best Practices for Working with Dictionary

  • Exception Handling: Handle potential exceptions, such as accessing non-existent keys.
  • Capacity Management: Set an appropriate initial capacity if the size is known beforehand.
  • Key Type: Use a key type that has proper hash codes to ensure consistent behavior.

Conclusion

The Dictionary<TKey, TValue> class in C# provides a flexible and efficient way to manage key-value pairs. By understanding its operations and best practices, you can leverage this collection to handle data efficiently in your applications.


 

Leave a reply Your email address will not be published. Required fields are marked*

Categories Clouds