0
0
C Sharp (C#)programming~5 mins

Dictionary key-value collection in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A dictionary stores pairs of keys and values so you can quickly find a value by its key.

When you want to look up a phone number by a person's name.
When you need to count how many times each word appears in a text.
When you want to store settings where each setting has a name and a value.
When you want to map product IDs to product details in a store.
When you want to cache data for fast access using unique keys.
Syntax
C Sharp (C#)
Dictionary<TKey, TValue> dictionaryName = new Dictionary<TKey, TValue>();
TKey is the type of the key, and TValue is the type of the value.
Keys must be unique; values can repeat.
Examples
This creates a dictionary where keys are names (strings) and values are ages (integers).
C Sharp (C#)
Dictionary<string, int> ages = new Dictionary<string, int>();
Adds a key "Alice" with value 30 to the dictionary.
C Sharp (C#)
ages.Add("Alice", 30);
Gets the age value for the key "Alice".
C Sharp (C#)
int age = ages["Alice"];
Checks if the key "Bob" exists in the dictionary.
C Sharp (C#)
bool hasBob = ages.ContainsKey("Bob");
Sample Program

This program creates a phone book dictionary, adds three contacts, and prints their numbers. It also lists all contacts.

C Sharp (C#)
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, string> phoneBook = new Dictionary<string, string>();
        phoneBook.Add("John", "555-1234");
        phoneBook.Add("Jane", "555-5678");
        phoneBook["Bob"] = "555-8765"; // Another way to add

        Console.WriteLine("John's number: " + phoneBook["John"]);

        if (phoneBook.ContainsKey("Jane"))
        {
            Console.WriteLine("Jane's number: " + phoneBook["Jane"]);
        }

        Console.WriteLine("All contacts:");
        foreach (var entry in phoneBook)
        {
            Console.WriteLine(entry.Key + ": " + entry.Value);
        }
    }
}
OutputSuccess
Important Notes

Trying to get a value with a key that does not exist will cause an error. Use ContainsKey to check first.

You can update a value by assigning a new value to an existing key.

Dictionaries are very fast for lookups compared to lists.

Summary

Dictionaries store data as key-value pairs for quick access.

Keys must be unique and are used to find values.

Use Add() to insert and indexer [] to get or set values.