Hashtable with multiple values for single key

后端 未结 11 1538
渐次进展
渐次进展 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:11

    You're looking for a Lookup, which can natively store multiple values for each key.

    As pointed out this only works for a fixed list since you cannot add entries to a lookup once you have created it.

    public class LookupEntry
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }
    
    var list = new List(new LookupEntry [] 
                                        {
                                        new LookupEntry() {Key="1", Value="Car" }, 
                                        new LookupEntry() {Key="1", Value="Truck"},
                                        new LookupEntry() {Key="2", Value="Duck"}
                                        });
    
    
    var lookup = list.ToLookup(x => x.Key, x => x.Value);
    var all1s = lookup["1"].ToList();
    

提交回复
热议问题