单个键具有多个值的哈希表

发布于 2024-10-09 17:43:38 字数 145 浏览 7 评论 0 原文

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

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

现在这会引发错误。

I want to store multiple values in single key like:

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

Right now this throws an error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

王权女流氓 2024-10-16 17:43:39

您最好使用两个哈希表,就像我在 这个库 中使用的那样

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

浅听莫相离 2024-10-16 17:43:38

您可以将 test,test1,test2,... 放入一个表中,然后将该表放入哈希表中作为键的值,该值对于所有这些键都是相同的。

例如尝试这样的事情:

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

然后:

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

you can put your test,test1,test2,... in a table and then put this table in a Hashtable as a value for the key which will be the same for all them.

For example try something like this:

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

and then:

HashTable obj = new HashTable();
obj.Add("1", list);
惜醉颜 2024-10-16 17:43:38

您不能在字典/哈希表中使用相同的键。
我认为你想为每个键使用一个列表,例如(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);

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);
情深缘浅 2024-10-16 17:43:38

我正在使用自己的 MultiDictionary 类。它基于 Dictionary> 但在此之上提供了一些语法糖。应该很容易扩展 Entry 来实现 IList

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);
        }
    }
}

I'm using my own MultiDictionary class. It's based on a Dictionary<TKey,List<TValue>> but offers a bit of syntax sugar on top of that. Should be easy to extent Entry<TValue> to implement 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);
        }
    }
}
我一向站在原地 2024-10-16 17:43:38

你可以使用字典。

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

示例代码:

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

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

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>;
黄昏下泛黄的笔记 2024-10-16 17:43:38

这会引发错误,因为您添加了相同的密钥两次。尝试使用 Dictionary 而不是 HashTable

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

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);
煮酒 2024-10-16 17:43:38

您正在寻找一个 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();

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<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();
如果没有 2024-10-16 17:43:38

可能是四年后的事了,但我希望它对以后的人有帮助。
正如本文前面提到的,在 Hashtable(key, value) 中不可能使用相同的键来表示不同的值。尽管如此,您可以创建一个列表或某个对象作为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

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

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
双马尾 2024-10-16 17:43:38

在哈希表中存储列表:

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

这是一个常见的技巧。

Store a list in the hashtable:

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

This is a common trick.

独享拥抱 2024-10-16 17:43:38

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

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

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" }
};
怎樣才叫好 2024-10-16 17:43:38

您可以使用 NameValueCollection - 与哈希表相同,并且具有“GetValues()”。

You can use NameValueCollection - works the same as hashtable and has the "GetValues()".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文