dictionary in c# programiz

dictionary in c# programiz
In this article [Show more]

    Dictionary in C# (Programiz)

    A Dictionary<TKey, TValue> in C# is a powerful collection that stores key-value pairs. It allows for efficient retrieval, insertion, and removal of elements based on their keys. This article provides a comprehensive overview of dictionaries in C#, offering practical examples and usage tips.

    Features of Dictionary<TKey, TValue>

    • Key-Value Pairs: Each key in the dictionary maps to a corresponding value.
    • Unique Keys: All keys are unique, preventing duplicates.
    • Efficient Access: Fast lookup and modification due to hash-based indexing.
    • Generic: Can hold any data types as long as they implement the required interfaces.

    Example: Creating and Using a Dictionary

    Basic Operations

    Here is how you can create a dictionary, add key-value pairs, retrieve values, and iterate through its items:

     

    using System;
    using System.Collections.Generic;
    
    public class DictionaryProgram
    {
        public static void Main()
        {
            // Create a dictionary with string keys and integer values
            Dictionary<string, int> fruits = new Dictionary<string, int>
            {
                { "Apple", 10 },
                { "Banana", 20 },
                { "Orange", 30 }
            };
    
            // Add a new key-value pair
            fruits["Pineapple"] = 40;
    
            // Access a value using the key
            int bananaCount = fruits["Banana"];
            Console.WriteLine($"Banana count: {bananaCount}");
    
            // Update an existing value
            fruits["Orange"] = 35;
    
            // Remove a key-value pair by key
            fruits.Remove("Apple");
    
            // Iterate through the dictionary using foreach
            Console.WriteLine("\nAll fruits in the dictionary:");
            foreach (KeyValuePair<string, int> fruit in fruits)
            {
                Console.WriteLine($"{fruit.Key}: {fruit.Value}");
            }
        }
    }
    

    Common Operations

    1. Add(key, value): Adds a new key-value pair to the dictionary.
    2. Remove(key): Deletes a key-value pair based on the key.
    3. ContainsKey(key): Checks if a key exists in the dictionary.
    4. TryGetValue(key, out value): Retrieves a value safely without throwing exceptions.
    5. Count: Returns the number of key-value pairs.
    6. Clear: Removes all pairs from the dictionary.

    Best Practices

    • Exception Handling: Handle exceptions gracefully when keys are not found.
    • TryGetValue: Prefer TryGetValue for safe retrieval.
    • Initial Capacity: Set an initial capacity if the size is known to minimize resizing.

    Advanced Use Cases

    • Configuration Settings: Store application configurations in key-value pairs.
    • Data Indexing: Index different attributes for quick search and filtering.

    Conclusion

    A Dictionary<TKey, TValue> in C# is an essential collection for efficient key-value storage. Understanding its features, operations, and best practices will help you build effective data structures tailored to your application's requirements.


     

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments