📜  C#|创建具有指定初始大小的区分大小写的HybridDictionary

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

HybridDictionary(Int32)构造函数用于创建具有指定初始大小的区分大小写的HybridDictionary。

句法:

public HybridDictionary (int initialSize);

在这里, initialSize是HybridDictionary最初可以包含的大约条目数。

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

范例1:

// C# code to create a case-sensitive
// HybridDictionary with the specified
// initial size.
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a case-sensitive HybridDictionary
        // with the specified initial size.
        HybridDictionary myDict = new HybridDictionary(10);
  
        // Adding key/value pairs in myDict
        myDict.Add("A", "Apple");
  
        // This will not raise exception as
        // By default, the collection is case-sensitive
        myDict.Add("a", "Air");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
  
        // This will not raise exception as
        // By default, the collection is case-sensitive
        myDict.Add("d", "Dolphine");
        myDict.Add("E", "Elephant");
        myDict.Add("F", "Fish");
  
        // Displaying the key/value pairs in myDict
        foreach(DictionaryEntry de in myDict)
            Console.WriteLine(de.Key + " " + de.Value);
    }
}

输出:

B Banana
a Air
A Apple
d Dolphine
C Cat
E Elephant
F Fish
D Dog

范例2:

// C# code to create a case-sensitive
// HybridDictionary with the specified
// initial size.
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a case-sensitive HybridDictionary
        // with the specified initial size.
        HybridDictionary myDict = new HybridDictionary(10);
  
        // Adding key/value pairs in myDict
        // As the HybridDictionary is case-sensitive
        // Therefore no exception is raised
        // Because "k1" & "K1" are taken as different keys
        // Similarly "k2" & "K2", "k3" & "K3"
        myDict.Add("k1", "v1");
        myDict.Add("K1", "v1");
        myDict.Add("k2", "v2");
        myDict.Add("K2", "v2");
        myDict.Add("k3", "v3");
        myDict.Add("K3", "v3");
  
        // Displaying the key/value pairs in myDict
        foreach(DictionaryEntry de in myDict)
            Console.WriteLine(de.Key + " " + de.Value);
    }
}

输出:

k3 v3
K3 v3
k2 v2
K2 v2
k1 v1
K1 v1

笔记:

  • 如果集合的初始大小大于ListDictionary的最佳大小,则将集合存储在Hashtable中,以避免将元素从ListDictionary复制到Hashtable的开销。
  • 默认情况下,该集合区分大小写。
  • HybridDictionary中的每个键都必须是唯一的。
  • 该构造函数是一个O(n)操作,其中n是initialSize