快速解决方案
正如您已经提到的,字典是最好的使用类型。您可以指定键类型和值类型以满足您的需要,在您的情况下,您需要一个 int 键和一个 List<int> 值。
这很容易创建:
Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>();
挑战随之而来的是你如何添加记录,你不能简单地做Add(key, value),因为这会导致重复键的冲突。因此,您必须首先检索列表(如果存在)并添加到该列表中:
List<int> list = null;
if (dictionary.ContainsKey(key))
{
list = dictionary[key];
}
else
{
list = new List<int>();
dictionary.Add(key, list);
}
list.Add(newValue);
首选解决方案
这显然是每次你想添加一个项目时使用的太多行,所以你想把它扔到一个辅助函数中,或者我更喜欢创建你自己的类来扩展字典的功能.像这样的:
class ListDictionary<T1, T2> : Dictionary<T1, List<T2>>
{
public void Add(T1 key, T2 value)
{
if (this.ContainsKey(key))
{
this[key].Add(value);
}
else
{
List<T2> list = new List<T2>() { value };
this.Add(key, list);
}
}
public List<T2> GetValues(T1 key)
{
if(this.ContainsKey(key))
return this[key];
return null;
}
}
然后您可以像最初想要的那样简单地使用它:
ListDictionary<int, int> myDictionary = new ListDictionary<int, int>();
myDictionary.Add(1,5);
myDictionary.Add(3,6);
//...and so on
然后获取所需键的值列表:
List<int> keyValues = myDictionary.GetValues(key);
//check if NULL before using, NULL means the key does not exist
//alternatively you can check if the key exists with if (myDictionary.ContainsKey(key))