📌  相关文章
📜  C#|将指定的键和值添加到ListDictionary

📅  最后修改于: 2021-05-29 22:33:42             🧑  作者: Mango

ListDictionary.Add(Object,Object)方法用于将具有指定键和值的条目添加到ListDictionary中。

句法:

public void Add (object key, object value);

参数:

例外情况:

  • ArgumentNullException:如果键为null。
  • ArgumentException:这是一个具有相同键的条目,该键已存在于ListDictionary中。

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to add an entry with
// the specified key and value
// into the ListDictionary
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();
  
        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 total number of elements in myDict
        Console.WriteLine("Total number of elements in myDict are : " 
                                                      + myDict.Count);
  
        // Displaying the elements in ListDictionary myDict
        foreach(DictionaryEntry de in myDict)
        {
            Console.WriteLine(de.Key + " " + de.Value);
        }
    }
}

输出:

Total number of elements in myDict are : 6
Australia Canberra
Belgium Brussels
Netherlands Amsterdam
China Beijing
Russia Moscow
India New Delhi

范例2:

// C# code to add an entry with
// the specified key and value
// into the ListDictionary
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();
  
        myDict.Add("Australia", "Canberra");
        myDict.Add("Belgium", "Brussels");
  
        // This should raise "ArgumentNullException"
        // as key is null
        myDict.Add(null, "Amsterdam");
  
        myDict.Add("China", "Beijing");
        myDict.Add("Russia", "Moscow");
        myDict.Add("India", "New Delhi");
  
        // Displaying the total number of elements in myDict
        Console.WriteLine("Total number of elements in myDict are : "
                                                     + myDict.Count);
  
        // Displaying the elements in ListDictionary myDict
        foreach(DictionaryEntry de in myDict)
        {
            Console.WriteLine(de.Key + " " + de.Value);
        }
    }
}

输出:

笔记:

  • 在其状态与其哈希码值之间不相关的对象通常不应用作键。例如,与用作键的String对象相比,String对象要好于StringBuilder对象。
  • 此方法是O(n)运算,其中n是Count。

参考:

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