How is a c# dictionary used?

In C#, a Dictionary is a collection of key-value pairs that allows access and manipulation of values through keys. It is a generic type that can store keys and values of any type.

Here are some common uses of the dictionary.

  1. Create a Dictionary object:
Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
  1. Add a key-value pair:
dictionary.Add(key, value);

Alternatively, you could use an indexer.

dictionary[key] = value;
  1. Get value:
TValue value = dictionary[key];
  1. Check if it contains a specified key:
bool containsKey = dictionary.ContainsKey(key);
  1. Get all keys or values.
ICollection<TKey> keys = dictionary.Keys;
ICollection<TValue> values = dictionary.Values;
  1. Iterating through a dictionary:
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
    TKey key = pair.Key;
    TValue value = pair.Value;
    // 进行操作
}
  1. Remove key-value pair:
bool removed = dictionary.Remove(key);
  1. clear the dictionary
dictionary.Clear();

A Dictionary is an efficient data structure that allows for quick searching and manipulation of key-value pairs. It is widely used in many scenarios such as caching and indexing.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds