Implements IDictionary by using a ListDictionary while the collection is small, and then switching to a Hashtable when the collection gets large. : IDictionary « Collections Data Structure « C# / C Sharp






Implements IDictionary by using a ListDictionary while the collection is small, and then switching to a Hashtable when the collection gets large.

 

using System;
using System.Collections;
using System.Collections.Specialized;

public class SamplesHybridDictionary  {

   public static void Main()  {

      HybridDictionary myCol = new HybridDictionary();
      myCol.Add( "A", "1.49" );
      myCol.Add( "B", "1.29" );
      myCol.Add( "C", "1.49" );

      PrintKeysAndValues1( myCol );
      PrintKeysAndValues2( myCol );
      PrintKeysAndValues3( myCol );

      DictionaryEntry[] myArr = new DictionaryEntry[myCol.Count];

      myCol.CopyTo( myArr, 0 );

      for ( int i = 0; i < myArr.Length; i++ )
         Console.WriteLine( "   {0,-25} {1}", myArr[i].Key, myArr[i].Value );

      if ( myCol.Contains( "A" ) )
         Console.WriteLine( "The collection contains the key A." );

      myCol.Remove( "A" );
      PrintKeysAndValues1( myCol );
      myCol.Clear();
   }

   public static void PrintKeysAndValues1( IDictionary myCol )  {
      foreach ( DictionaryEntry de in myCol )
         Console.WriteLine( "   {0,-25} {1}", de.Key, de.Value );
   }

   public static void PrintKeysAndValues2( IDictionary myCol )  {
      IDictionaryEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         Console.WriteLine( "   {0,-25} {1}", myEnumerator.Key, myEnumerator.Value );
   }

   public static void PrintKeysAndValues3( HybridDictionary myCol )  {
      String[] myKeys = new String[myCol.Count];
      myCol.Keys.CopyTo( myKeys, 0 );
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( "   {0,-5} {1,-25} {2}", i, myKeys[i], myCol[myKeys[i]] );
   }

}

   
  








Related examples in the same category