C#(.NET 6)中的字典与哈希表:详细指南
Dictionaries and Hash Tables in C#
What is a dictionary and why is it needed?
Imagine you have a magic notebook. In a regular notebook, you can write down a friend's name and their phone number. When you need to call, you look up the name in the notebook and find the number. A dictionary in programming works exactly the same way!
A Dictionary is a collection that stores "key — value" pairs. The key is what we search by (for example, a friend's name), and the value is what we are looking for (the phone number).
The main advantage of a dictionary is very fast lookup. It doesn't matter if the dictionary stores 10 entries or 10,000 — searching by key happens almost instantly. This is possible thanks to a special data structure called a hash table.
How to create and use a dictionary
In C#, the dictionary is called Dictionary, where TKey is the key type and TValue is the value type.
// Creating an empty dictionary where the key is a string (name) and the value is a string (phone number)
Dictionary<string, string> phoneBook = new Dictionary<string, string>();
// Adding entries
phoneBook.Add("Anna", "+7-912-345-67-89");
phoneBook.Add("Peter", "+7-923-456-78-90");
// Getting a value by key
string petePhone = phoneBook["Peter"];
Console.WriteLine($"Peter's phone: {petePhone}");
// Checking if a key exists in the dictionary
if (phoneBook.ContainsKey("Anna"))
{
Console.WriteLine("Anna is in the phonebook!");
}
// Changing a value
phoneBook["Anna"] = "+7-999-888-77-66";
// Deleting an entry
phoneBook.Remove("Peter");
Another way to create a dictionary
You can create a dictionary with initial data right away:
Dictionary<string, string> greetings = new Dictionary<string, string>()
{
{ "Russia", "Hello!" },
{ "France", "Bonjour!" },
{ "Italy", "Ciao!" },
{ "England", "Hello!" }
};
Console.WriteLine($"In England they say: {greetings["England"]}");
Iterating over all dictionary elements
To go through all entries in a dictionary, we use a foreach loop. Each element is a KeyValuePair that has Key and Value properties.
Dictionary<string, int> products = new Dictionary<string, int>()
{
{ "Bread", 45 },
{ "Milk", 80 },
{ "Apples", 120 }
};
Console.WriteLine("Our products:");
foreach (var item in products)
{
Console.WriteLine($"{item.Key} costs {item.Value} rubles");
}
Program output:
Our products:
Bread costs 45 rubles
Milk costs 80 rubles
Apples costs 120 rubles
Dictionary with a list of values
Sometimes you need one key to have multiple values. For example, for each day of the week — a list of tasks. For this, you can use a dictionary where the value is a list (List).
// Dictionary where the key is a day of the week, the value is a list of tasks
Dictionary<string, List<string>> weeklyPlan = new Dictionary<string, List<string>>();
// Adding a list of tasks for Monday
weeklyPlan["Monday"] = new List<string>() { "Do homework", "Feed the cat" };
// Adding another task for Monday
weeklyPlan["Monday"].Add("Read a book");
// Adding Tuesday
weeklyPlan["Tuesday"] = new List<string>() { "Go to the pool" };
// Printing all tasks for Monday
Console.WriteLine("Tasks for Monday:");
foreach (string task in weeklyPlan["Monday"])
{
Console.WriteLine($"- {task}");
}
Analysis of typical tasks
Task 1: Phonebook
Need to find a phone number by name. If the name is not found — report it.
Dictionary<string, string> phoneBook = new Dictionary<string, string>()
{
{ "Masha", "8-912-345-67-89" },
{ "Sasha", "8-923-456-78-90" },
{ "Dasha", "8-934-567-89-01" }
};
Console.Write("Enter a name to search for: ");
string name = Console.ReadLine();
if (phoneBook.ContainsKey(name))
{
Console.WriteLine($"Phone number for {name}: {phoneBook[name]}");
}
else
{
Console.WriteLine("This name is not in the phonebook");
}
Task 2: Deleting a contact
The user enters a name, and the program deletes that contact from the dictionary.
Dictionary<string, string> contacts = new Dictionary<string, string>()
{
{ "Ivan", "8-111-222-33-44" },
{ "Maria", "8-555-666-77-88" },
{ "Alexey", "8-999-000-11-22" }
};
Console.Write("Enter the contact name to delete: ");
string nameToDelete = Console.ReadLine();
if (contacts.Remove(nameToDelete))
{
Console.WriteLine($"Contact '{nameToDelete}' deleted!");
}
else
{
Console.WriteLine($"Contact '{nameToDelete}' does not exist");
}
// Showing remaining contacts
Console.WriteLine("Remaining contacts:");
foreach (var contact in contacts)
{
Console.WriteLine($"{contact.Key}: {contact.Value}");
}
Task 3: Printing all dictionary keys
The program prints a list of all products (names only) from the dictionary.
Dictionary<string, int> store = new Dictionary<string, int>()
{
{ "Apples", 150 },
{ "Bananas", 120 },
{ "Oranges", 180 },
{ "Grapes", 250 }
};
Console.WriteLine("List of available products:");
foreach (string productName in store.Keys) // Keys is a collection of all keys
{
Console.WriteLine($"- {productName}");
}
Common beginner mistakes
Mistake 1: Accessing a non-existent key
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Vasya"] = 10;
// Error! The key "Petya" is not in the dictionary
// Console.WriteLine(ages["Petya"]); // Will throw an exception!
// Correct: check first
if (ages.ContainsKey("Petya"))
{
Console.WriteLine(ages["Petya"]);
}
Mistake 2: Adding