具有单个键的多个值的Hashtable

时间:2010-12-29 13:24:05

标签: c# hashtable multiple-value

我想在单个键中存储多个值,如:

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

现在这会引发错误。

11 个答案:

答案 0 :(得分:8)

你可以将你的test,test1,test2,...放在一个表中,然后把这个表放在一个Hashtable中作为键的值,这对于所有它们都是相同的。

例如尝试这样的事情:

List<string> list = new List<string>();
list.Add("test");
list.Add("test1"); 

然后:

HashTable obj = new HashTable();
obj.Add("1", list);

答案 1 :(得分:6)

您不能在Dictionary / Hashtable中使用相同的键。 我想你想为每个键使用List,例如(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);

答案 2 :(得分:4)

我正在使用自己的MultiDictionary课程。它基于Dictionary<TKey,List<TValue>>,但在此基础上提供了一些语法糖。应该很容易Entry<TValue>来实施IList<T>

public class MultiDictionary<TKey, TValue>
{
    private Dictionary<TKey, List<TValue>> data = new Dictionary<TKey, List<TValue>>();

    public struct Entry : IEnumerable<TValue>
    {
        private readonly MultiDictionary<TKey, TValue> mDictionary;
        private readonly TKey mKey;

        public TKey Key { get { return mKey; } }

        public bool IsEmpty
        {
            get
            {
                return !mDictionary.data.ContainsKey(Key);
            }
        }

        public void Add(TValue value)
        {
            List<TValue> list;
            if (!mDictionary.data.TryGetValue(Key, out list))
                list = new List<TValue>();
            list.Add(value);
            mDictionary.data[Key] = list;
        }

        public bool Remove(TValue value)
        {
            List<TValue> list;
            if (!mDictionary.data.TryGetValue(Key, out list))
                return false;
            bool result = list.Remove(value);
            if (list.Count == 0)
                mDictionary.data.Remove(Key);
            return result;
        }

        public void Clear()
        {
            mDictionary.data.Remove(Key);
        }

        internal Entry(MultiDictionary<TKey, TValue> dictionary, TKey key)
        {
            mDictionary = dictionary;
            mKey = key;
        }

        public IEnumerator<TValue> GetEnumerator()
        {
            List<TValue> list;
            if (!mDictionary.data.TryGetValue(Key, out list))
                return Enumerable.Empty<TValue>().GetEnumerator();
            else
                return list.GetEnumerator();
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public Entry this[TKey key]
    {
        get
        {
            return new Entry(this, key);
        }
    }
}

答案 3 :(得分:1)

你可以使用字典。

实际上,您刚刚描述的是Dictionary集合的理想用法。无论值的类型如何,它都应该包含键:值对。通过将值设为自己的类,如果需要,您将来可以轻松扩展它。

示例代码:

class MappedValue
{
    public string SomeString { get; set; }
    public bool SomeBool { get; set; }
}

Dictionary<string, MappedValue> myList = new Dictionary<string, MappedValue>;

答案 4 :(得分:1)

因为你要两次添加相同的密钥而引发错误。尝试使用Dictionary代替HashTable

Dictionary<int, IList<string>> values = new Dictionary<int, IList<string>>();
IList<string> list = new List<string>()
{
    "test", "Test1"
};
values.Add(1, list);

答案 5 :(得分:1)

可能是4年后,但我希望以后可以帮助别人。 如前文所述,在Hashtable(键,值)中使用相同键 不同值不可能。但是,您可以在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<SomeObject> list = new List<someObject>();

//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]);

然后检索这些数据:

//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

答案 6 :(得分:0)

将列表存储在哈希表中:

obj.Add("1",new List<string>());
(obj["1"] as List<string>).Add("test");
(obj["1"] as List<string>).Add("test1");

这是一个常见的伎俩。

答案 7 :(得分:0)

您正在寻找Lookup,它可以为每个密钥本机存储多个值。

正如所指出的,这仅适用于固定列表,因为一旦创建了条目,就无法向查找添加条目。

public class LookupEntry
{
    public string Key { get; set; }
    public string Value { get; set; }
}

var list = new List<LookupEntry>(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();

答案 8 :(得分:0)

JFYI,你可以这样声明你的词:

Dictionary<int, IList<string>> dic = new
{
    { 1, new List<string> { "Test1", "test1" },
    { 2, new List<string> { "Test2", "test2" }
};

答案 9 :(得分:0)

您可以使用NameValueCollection - 与hashtable的工作方式相同,并具有“GetValues()”。

答案 10 :(得分:0)

最好使用我在this library

中使用的两个哈希表
相关问题