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

📅  最后修改于: 2021-05-29 13:48:45             🧑  作者: Mango

HybridDictionary(Int32,Boolean)创建具有指定初始大小和区分大小写的HybridDictionary。

句法:

public HybridDictionary (int initialSize, bool caseInsensitive);

参数:

  • initialSize: HybridDictionary最初可以包含的大约条目数。
  • caseInsensitive:一个布尔值,指示HybridDictionary是否不区分大小写。

下面的程序说明了HybridDictionary(Int32,Boolean)的用法:

范例1:

// C# code to create a HybridDictionary
// with the specified initial size
// and case sensitivity.
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HybridDictionary with the
        // specified initial size and case sensitivity.
        HybridDictionary myDict = new HybridDictionary(10, false);
  
        // Adding key/value pairs in myDict
        myDict.Add("I", "first");
  
        // This will not raise exception as the
        // Collection is not case-insensitive
        myDict.Add("i", "first");
        myDict.Add("II", "second");
        myDict.Add("III", "third");
        myDict.Add("IV", "fourth");
        myDict.Add("V", "fifth");
  
        // Displaying the key/value pairs in myDict
        foreach(DictionaryEntry de in myDict)
            Console.WriteLine(de.Key + " " + de.Value);
    }
}

输出:

III third
V fifth
II second
i first
I first
IV fourth

范例2:

// C# code to create a HybridDictionary
// with the specified initial size
// and case sensitivity.
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HybridDictionary with the
        // specified initial size and case sensitivity.
        HybridDictionary myDict = new HybridDictionary(10, true);
  
        // Adding key/value pairs in myDict
        myDict.Add("A", "Apple");
  
        // This will raise exception as the
        // Collection is case-insensitive
        myDict.Add("a", "Air");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
        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);
    }
}

运行时错误:

笔记:

  • 如果集合的初始大小大于ListDictionary的最佳大小,则将集合存储在Hashtable中,以避免将元素从ListDictionary复制到Hashtable的开销。
  • 该构造函数是一个O(n)操作,其中n是initialSize