use*_*168 11 c# hashtable multiple-value
我想在单个键中存储多个值,如:
HashTable obj = new HashTable();
obj.Add("1", "test");
obj.Add("1", "Test1");
Run Code Online (Sandbox Code Playgroud)
现在这会引发错误.
你可以将你test,test1,test2,...的表放在一个表中,然后把这个表放在一个Hashtable中作为键的值,这对于所有它们都是相同的.
例如尝试这样的事情:
List<string> list = new List<string>();
list.Add("test");
list.Add("test1");
Run Code Online (Sandbox Code Playgroud)
然后:
HashTable obj = new HashTable();
obj.Add("1", list);
Run Code Online (Sandbox Code Playgroud)
您不能在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)
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
我正在使用我自己的MultiDictionary课程。它基于 aDictionary<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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用字典。
实际上,您刚才描述的是 Dictionary 集合的理想用途。它应该包含键:值对,无论值的类型如何。通过将值设为自己的类,您将来可以在需要时轻松扩展它。
示例代码:
class MappedValue
{
public string SomeString { get; set; }
public bool SomeBool { get; set; }
}
Dictionary<string, MappedValue> myList = new Dictionary<string, MappedValue>;
Run Code Online (Sandbox Code Playgroud)