C# Dictionary
A Dictionary
is a collection type that allows you to store key-value pairs. It is part of the System.Collections.Generic
namespace.
The Dictionary<TKey, TValue>
class provides fast lookups and is useful when you need to associate values with unique keys.
Here's a basic overview of how to use a Dictionary
in C#.
Creating a Dictionary
You can create a dictionary by specifying the types for keys (TKey
) and values (TValue
).
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a dictionary with string keys and int values
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
// Adding key-value pairs
myDictionary.Add("one", 1);
myDictionary.Add("two", 2);
myDictionary.Add("three", 3);
// Accessing values by key
Console.WriteLine(myDictionary["two"]); // Output: 2
}
}
Initializing a Dictionary with Initial Values
You can initialize a dictionary with initial values using a collection initializer.
Dictionary<string, int> myDictionary = new Dictionary<string, int>
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 }
};
Checking if a Key Exists
You can check if a key exists in the dictionary before accessing its value to avoid exceptions.
if (myDictionary.ContainsKey("two"))
{
int value = myDictionary["two"];
Console.WriteLine(value); // Output: 2
}
Iterating Through a Dictionary
You can iterate through the keys and values of a dictionary using a foreach loop.
foreach (var kvp in myDictionary)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
Removing Items from a Dictionary
You can remove items from a dictionary using the Remove
method.
myDictionary.Remove("two");
More Dictionary Methods
The Dictionary<TKey, TValue>
class provides various methods for working with dictionaries, such as TryGetValue
, ContainsKey
, Count
, Clear
, etc. You can explore these methods based on your requirements.
// Example of using TryGetValue
int value;
if (myDictionary.TryGetValue("two", out value))
{
Console.WriteLine(value); // Output: 2
}
These are some basic operations you can perform with a C# Dictionary
. It's a powerful and flexible data structure for handling key-value pairs efficiently.