.NET API Documentation

IDictionary<TKey, TValue> Interface

Represents a collection of key/value pairs that are sorted by key. This interface is inherited by the SortedDictionary<TKey, TValue> class.

The IDictionary<TKey, TValue> interface represents a generic collection of key-value pairs, where each key is unique. It provides methods for adding, removing, and retrieving elements based on their keys.

Syntax

public interface IDictionary<TKey,TValue> : ICollection<KeyValuePair<TKey,TValue>>, IEnumerable<KeyValuePair<TKey,TValue>>, IEnumerable

Type Parameters:

Members

Examples

Here's a basic example of how to use a dictionary:

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main(string[] args)
    {
        // Create a dictionary
        IDictionary<string, int> scores = new Dictionary<string, int>();

        // Add elements
        scores.Add("Alice", 95);
        scores.Add("Bob", 88);
        scores.Add("Charlie", 92);

        // Access elements by key
        Console.WriteLine($"Alice's score: {scores["Alice"]}");

        // Check if a key exists
        if (scores.ContainsKey("Bob"))
        {
            Console.WriteLine("Bob is in the dictionary.");
        }

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

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

        // Try to get a value that might not exist
        if (scores.TryGetValue("David", out int davidScore))
        {
            Console.WriteLine($"David's score: {davidScore}");
        }
        else
        {
            Console.WriteLine("David not found in the dictionary.");
        }
    }
}