Hashtable with multiple values for single key

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

    JFYI, you can declare your dic this way:

    Dictionary<int, IList<string>> dic = new
    {
        { 1, new List<string> { "Test1", "test1" },
        { 2, new List<string> { "Test2", "test2" }
    };
    
    0 讨论(0)
  • 2021-02-13 14:20

    You can't use the same key in a Dictionary/Hashtable. I think you want to use a List for every key, for example (VB.NET):

    Dim dic As New Dictionary(Of String, List(Of String))
    Dim myValues As New List(Of String)
    myValues.Add("test")
    myValues.Add("Test1")
    dic.Add("1", myValues)
    

    C#:

    Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
    List<string> myValues = new List<string>();
    myValues.Add("test");
    myValues.Add("Test1");
    dic.Add("1", myValues);
    
    0 讨论(0)
  • 2021-02-13 14:20

    That throws an error because you're adding the same key twice. Try using a Dictionary instead of a HashTable.

    Dictionary<int, IList<string>> values = new Dictionary<int, IList<string>>();
    IList<string> list = new List<string>()
    {
        "test", "Test1"
    };
    values.Add(1, list);
    
    0 讨论(0)
  • 2021-02-13 14:23

    It would be better for you to use two hashtables as I've used in this library

    0 讨论(0)
  • 2021-02-13 14:29

    You could use a dictionary.

    Actually, what you've just described is an ideal use for the Dictionary collection. It's supposed to contain key:value pairs, regardless of the type of value. By making the value its own class, you'll be able to extend it easily in the future, should the need arise.

    Sample code:

    class MappedValue
    {
        public string SomeString { get; set; }
        public bool SomeBool { get; set; }
    }
    
    Dictionary<string, MappedValue> myList = new Dictionary<string, MappedValue>;
    
    0 讨论(0)
提交回复
热议问题