📅  最后修改于: 2023-12-03 15:29:05.483000             🧑  作者: Mango
In C#, a Dictionary is a collection type that is used to store Key/Value pairs, where Keys must be unique within a dictionary. It provides a fast lookup of values based on unique keys.
The syntax to declare a Dictionary in C# is as follows:
Dictionary<TKey, TValue> dictionaryName = new Dictionary<TKey, TValue>();
Here, TKey
is the type of the key and TValue
is the type of the value that will be stored in the dictionary.
Let's say we want to create a dictionary to store the names and ages of some people. We can declare the dictionary as follows:
Dictionary<string, int> people = new Dictionary<string, int>();
Now, we can add items to the dictionary like this:
people.Add("John", 25);
people.Add("Jane", 30);
people.Add("Bob", 28);
We can access the values in the dictionary using the keys like this:
int johnsAge = people["John"];
int janesAge = people["Jane"];
int bobsAge = people["Bob"];
We can also use the TryGetValue()
method to check if a key exists in the dictionary and get its value if it does:
int age;
if (people.TryGetValue("John", out age))
{
Console.WriteLine("John's age is {0}.", age);
}
else
{
Console.WriteLine("John not found in the dictionary.");
}
In conclusion, the Dictionary is a useful collection type in C# for storing Key/Value pairs, where keys must be unique. It provides a fast lookup of values based on keys, making it an ideal choice for many programming scenarios.