Search code examples
c#hashtable

How to AddRange in a HashTable?


HashTable list = new HashTable();
list.Add(1,"green");
list.Add(2,"blue");
list.Add(3,"red");

How to add these items like addrange in a HashTable?


Solution

  • Although there is no AddRange for a HashTable, you could create an extension to at least mimic the AddRange behaviour. This is a quick answer to hopefully get you going, by no means this isn't the best implementation as there are other alternatives.

    Here's an example extension -

     public static void AddRange<T, K>(this Hashtable hash, IEnumerable<KeyValuePair<T,K>> ikv)
     {
         foreach(KeyValuePair<T, K> kvp in ikv)
         {
            if (!hash.ContainsKey(kvp.Key))
            {
               hash.Add(kvp.Key, kvp.Value);                    
            }                
         }
     }
    

    Here's one way you can use it -

    Hashtable list = new Hashtable();
    list.AddRange(new[] { new KeyValuePair<int, string>(1,"green"), new KeyValuePair<int, string>(2,"blue"), new KeyValuePair<int, string>(3,"red") });
    

    Again, this was a quick example to help you out, hopefully it's enough to get you going.