SoFunction
Updated on 2025-04-11

Common operations of Dictionary in C#

Basic concepts

Dictionary<TKey, TValue>It is a generic class used in C# to store a collection of key-value pairs, belonging toNamespace. It allows the use of keys (Key) to access the value associated with it (Value). Where, TKey represents the type of the key in the dictionary, and TValue represents the type of the value in the dictionary.

The basic structure of Dictionary

  • Key: A key uniquely identifies an element in the collection. The key is unique and cannot be repeated.
  • Value: Data associated with the key. The value can be of any type and can be repeated.
  • KeyValuePair: A combination of keys and values, representing an element in the Dictionary.

The main features of Dictionary

  • Quick access: The corresponding value can be quickly retrieved through the key, and the average time complexity is close to O(1), becauseDictionary<TKey,TValue>Classes are implemented as hash tables.
  • Unique key: Each key is unique in Dictionary and cannot be repeated.
  • Dynamic size: The size of the Dictionary can be adjusted dynamically, and it will automatically expand when the number of elements exceeds the capacity.
  • Unordered collection: Elements in Dictionary are unordered and cannot be accessed through indexes.

Common operations of Dictionary

The following is the complete code of commonly used operations of Dictionary in C#, including adding elements, accessing elements, modifying elements, deleting elements, checking whether keys or values ​​exist, and traversing elements:

public static void DictionaryOperation()
{
    //Create a Dictionary to store student ID and name    Dictionary&lt;int, string&gt; studentDic = new Dictionary&lt;int, string&gt;();
    #region Add elements    // Add method (key must be unique)    (1, "Yao");
    (2, "Little Yuan");
    (3, "Edwin");
    // Indexer syntax (add when the key does not exist, update when it exists)    studentDic[4] = "Charlie";
    studentDic[5] = "Time Chaser";
    // Safely add (avoid exceptions)    bool isAdded = (6, "Xiao Ming"); // Return false because the key already exists    #endregion
    #region Access elements    // Direct access (the key must exist, otherwise there will be exceptions)    var currentUserName = studentDic[1];
    ($"Current student name: {currentUserName}");
    // Secure access (avoid exceptions)    if ((5, outvar getUserName))
    {
        ($"UserName:{getUserName}");
    }
    else
    {
        ("The current student ID does not exist");
    }
    #endregion
    #region
    // Modify elements    studentDic[2] = "Big Watermelon";
    ($"Modified name:{studentDic[2]}");
    #endregion
    #region Delete elements    // Delete elements    bool isRemoved = (3);
    ($"Delete the result:{isRemoved}");
    #endregion
    #region Check whether the key or value exists    // Check if the key exists    if ((1))
    {
        ("exist");
    }
    else
    {
        ("Not exists");
    }
    bool isExistcontainsValue = ("Time Chaser");
    ($"Does it exist:{isExistcontainsValue}");
    #endregion
    #region traversal elements    // traverse elements    foreach (KeyValuePair&lt;int, string&gt; student in studentDic)
    {
        ($"ID: {}, Name: {}");
    }
    // Enumerator using keys    foreach (var key in )
    {
        ($"Key: {key}, Value: {studentDic[key]}");
    }
    // Enumerator using values    foreach (varvaluein )
    {
        // Note: This method cannot directly obtain keys, only values ​​can be obtained        ($"Value: {value}");
    }
    #endregion
}

Reference article

  • /zh-cn/dotnet/api/-2?view=net-9.0

This is the end of this article about the commonly used operations of Dictionary in C#. For more related C# Dictionary content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!