-2
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?

Renzo Rodrigues
  • 553
  • 2
  • 9
  • 19

2 Answers2

1

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.

Trevor
  • 7,777
  • 6
  • 31
  • 50
1
    Hashtable list = new Hashtable
    {
        {1, "green"}, {2, "blue"}, {3, "red"}
    };

    // ICollection for keys 
    ICollection collection = list.Keys;

    // Write all
    foreach (var myList in collection)
        Console.WriteLine(myList + " - " + list[myList]);
Umut D.
  • 1,746
  • 23
  • 24