📌  相关文章
📜  C#|获取或设置与ListDictionary中的指定键关联的值

📅  最后修改于: 2021-05-29 15:04:18             🧑  作者: Mango

ListDictionary.Item [Object]属性用于获取或设置与指定键关联的值。

句法:

public object this[object key] { get; set; }

在此, key是要获取或设置其值的键。

返回值:与指定键关联的值。如果找不到指定的键,则尝试获取它会返回null ,然后尝试设置它会使用指定的键创建一个新条目。

异常:如果为null,则此属性将提供ArgumentNullException。

例子:

// C# code to get or set the value
// associated with the specified key
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a ListDictionary named myDict
        ListDictionary myDict = new ListDictionary();
  
        // Adding key/value pairs in myDict
        myDict.Add("Australia", "Canberra");
        myDict.Add("Belgium", "Brussels");
        myDict.Add("Netherlands", "Amsterdam");
        myDict.Add("China", "Beijing");
        myDict.Add("Russia", "Moscow");
        myDict.Add("India", "New Delhi");
  
        // Displaying the key/value pairs in myDict
        foreach(DictionaryEntry de in myDict)
        {
            Console.WriteLine(de.Key + " " + de.Value);
        }
  
        // Displaying the value associated
        // with key "Russia"
        Console.WriteLine(myDict["Russia"]);
  
        // Setting the value associated with key "Russia"
        myDict["Russia"] = "Saint Petersburg";
  
        // Displaying the value associated
        // with key "Russia"
        Console.WriteLine(myDict["Russia"]);
  
        // Displaying the value associated
        // with key "India"
        Console.WriteLine(myDict["India"]);
  
        // Setting the value associated with key "India"
        myDict["India"] = "Mumbai";
  
        // Displaying the value associated
        // with key "India"
        Console.WriteLine(myDict["India"]);
  
        // Displaying the key/value pairs in myDict
        foreach(DictionaryEntry de in myDict)
        {
            Console.WriteLine(de.Key + " " + de.Value);
        }
    }
}

输出:

Australia Canberra
Belgium Brussels
Netherlands Amsterdam
China Beijing
Russia Moscow
India New Delhi
Moscow
Saint Petersburg
New Delhi
Mumbai
Australia Canberra
Belgium Brussels
Netherlands Amsterdam
China Beijing
Russia Saint Petersburg
India Mumbai

笔记:

  • 通过使用以下语法,可以使用此属性访问集合中的特定元素: myCollection [key]
  • 键不能为null ,但值可以。
  • 此方法是O(n)运算,其中n是Count。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.listdictionary.item?view=netframework-4.7.2