Hashtable with multiple values for single key

后端 未结 11 1555
渐次进展
渐次进展 2021-02-13 13:36

I want to store multiple values in single key like:

HashTable obj = new HashTable();
obj.Add(\"1\", \"test\");
obj.Add(\"1\", \"Test1\");

Right

11条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 14:03

    Probably it is 4 years later, but I hope it will help somebody later. As mentioned earlier in the post, it is not possible to use the same key for different values in Hashtable(key, value). Although, you may create a List or some object as a value in the key/value pair of HashTable.

    //instantiate new Hashtable
    Hashtable hashtable = new Hashtable();
    
    //create a class that would represent a value in the HashTable
    public class SomeObject
    {
        public string value1 { get; set;}
        public string value2 { get; set;}
    }
    
    //create a List that would store our objects
    List list = new List();
    
    //add new items to the created list
    list.Add(new SomeObject() 
                 { 
                     value1 = "test", 
                     value2 = "test1"
                 });
    list.Add(new SomeObject() 
                 {
                     value1 = "secondObject_value1" 
                     value2 = "secondObject_value2"
                 })
    
    //add key/value pairs to the Hashtable.
    hashTable.Add("1", list[0]);
    hashTable.Add("2", list[1]);
    

    Then to retrieve this data:

    //retrieve the value for the key "1"
    SomeObject firstObj = (SomeObject)hashTable[1];
    //retrieve the value for the key "2"
    SomeObject secondObj = (SomeObject)hashTable[2];
    Console.WriteLine("Values of the first object are: {0} and {1}", 
                                                 firstObj.value1,firstObj.value2);
    Console.WriteLine("Values of the second object are {0} and {1}",
                                                 secondObj.value1, secondObj.value2);
    // output for the WriteLine:
    Values of the first object are: test and test1
    Values of the second object are secondObject_value1 and secondObject_value2
    

提交回复
热议问题