Dictionaries - potatoscript/csharp GitHub Wiki
π₯ Dictionaries in C# π₯
π₯ What is a Dictionary? π₯
A Dictionary in C# is like a phone book, but instead of names and phone numbers, it stores key-value pairs. The key is a unique identifier (like a name or a code), and the value is the information associated with that key (like a phone number or an address).
In a Dictionary, you can look up a value by its key, just like searching for someone's phone number using their name in a phone book. Unlike a List, where the items are accessed by index, you access items in a Dictionary by their key.
π₯ Why Use Dictionaries? π₯
- Quick Lookups: You can easily find a value if you know its key, making Dictionaries very efficient for searching.
- Unique Keys: Each key in a Dictionary must be unique, which prevents duplicate entries.
- Store Data: Great for when you need to store pairs of related data, like names and ages, product IDs and prices, etc.
π₯ Creating a Dictionary π₯
To use a Dictionary in C#, you need to import the System.Collections.Generic
namespace, just like you do with Lists.
Hereβs how to create a Dictionary:
// Importing the necessary namespace
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a Dictionary with string keys and int values
Dictionary<string, int> phoneBook = new Dictionary<string, int>();
// Adding items to the Dictionary
phoneBook.Add("Alice", 123456);
phoneBook.Add("Bob", 987654);
phoneBook.Add("Charlie", 555666);
// Displaying the contents of the Dictionary
foreach (var entry in phoneBook)
{
Console.WriteLine(entry.Key + ": " + entry.Value); // Output: Alice: 123456, Bob: 987654, Charlie: 555666
}
}
}
π₯ Adding Items to a Dictionary π₯
You can add items to a Dictionary using the .Add()
method. The .Add()
method requires a key and a value.
Dictionary<string, string> fruits = new Dictionary<string, string>();
// Adding items to the Dictionary
fruits.Add("Apple", "Red");
fruits.Add("Banana", "Yellow");
fruits.Add("Grape", "Purple");
// Displaying items
foreach (var fruit in fruits)
{
Console.WriteLine(fruit.Key + " is " + fruit.Value); // Output: Apple is Red, Banana is Yellow, Grape is Purple
}
π₯ Accessing Items in a Dictionary π₯
To access a value, you can use the key inside square brackets []
:
Dictionary<string, string> fruits = new Dictionary<string, string> { { "Apple", "Red" }, { "Banana", "Yellow" } };
// Accessing items using the key
Console.WriteLine(fruits["Apple"]); // Output: Red
Console.WriteLine(fruits["Banana"]); // Output: Yellow
π₯ Checking if a Key Exists π₯
Before accessing a value, you can check if the key exists in the Dictionary to avoid errors.
Dictionary<string, int> phoneBook = new Dictionary<string, int> { { "Alice", 123456 }, { "Bob", 987654 } };
// Checking if a key exists
if (phoneBook.ContainsKey("Alice"))
{
Console.WriteLine("Alice's phone number is: " + phoneBook["Alice"]);
}
else
{
Console.WriteLine("Alice is not in the phone book.");
}
π₯ Removing Items from a Dictionary π₯
You can remove items from a Dictionary using the .Remove()
method, which takes the key of the item to be removed.
Dictionary<string, string> fruits = new Dictionary<string, string> { { "Apple", "Red" }, { "Banana", "Yellow" } };
// Removing an item using its key
fruits.Remove("Banana");
// Displaying the Dictionary after removal
foreach (var fruit in fruits)
{
Console.WriteLine(fruit.Key + " is " + fruit.Value); // Output: Apple is Red
}
π₯ Updating Values in a Dictionary π₯
You can update a value by accessing the Dictionary using the key and assigning a new value to it.
Dictionary<string, string> fruits = new Dictionary<string, string> { { "Apple", "Red" }, { "Banana", "Yellow" } };
// Updating the value of a key
fruits["Apple"] = "Green";
// Displaying updated values
foreach (var fruit in fruits)
{
Console.WriteLine(fruit.Key + " is " + fruit.Value); // Output: Apple is Green, Banana is Yellow
}
π₯ Looping Through a Dictionary π₯
You can use a foreach loop to go through each key-value pair in the Dictionary.
Dictionary<string, string> fruits = new Dictionary<string, string> { { "Apple", "Red" }, { "Banana", "Yellow" } };
// Looping through the Dictionary
foreach (var entry in fruits)
{
Console.WriteLine(entry.Key + " is " + entry.Value); // Output: Apple is Red, Banana is Yellow
}
π₯ Other Useful Methods for Dictionaries π₯
Here are some other useful methods you can use with Dictionaries:
.Count
: Returns the number of key-value pairs in the Dictionary..Clear()
: Removes all items from the Dictionary..TryGetValue()
: Attempts to get the value for a given key without throwing an exception if the key doesn't exist.
Dictionary<string, string> fruits = new Dictionary<string, string> { { "Apple", "Red" }, { "Banana", "Yellow" } };
// Getting the count of items in the Dictionary
Console.WriteLine("Number of items: " + fruits.Count); // Output: 2
// Clearing the Dictionary
fruits.Clear();
Console.WriteLine("Number of items after clearing: " + fruits.Count); // Output: 0
// Using TryGetValue to safely get a value
if (fruits.TryGetValue("Apple", out string value))
{
Console.WriteLine("Apple is " + value);
}
else
{
Console.WriteLine("Apple is not found.");
}
π₯ When to Use Dictionaries? π₯
You should use a Dictionary when:
- You need to look up values quickly by a unique key (e.g., finding someone's phone number by their name).
- You need to store related pairs of data (e.g., name and age, country and capital).
- You want to avoid duplicates in your collection because keys must be unique.
π₯ Dictionary vs. List π₯
- Dictionaries are best when you need to map keys to values (like looking up a wordβs meaning in a dictionary). You can quickly search for values using keys.
- Lists are best for ordered collections where you need to access items by index or iterate through the items in a specific order.
π₯ Summary of Dictionaries in C# π₯
- A Dictionary stores pairs of data, called key-value pairs.
- Each key in the Dictionary must be unique.
- You can access values by their keys, add new pairs, remove pairs, and update values.
- Dictionaries are great for scenarios where quick lookup by a unique key is needed.