MSDN解释了这样的Lookup:
一个
Lookup<TKey, TElement>
酷似Dictionary<TKey, TValue>
.不同之处在于 Dictionary <TKey,TValue>将键映射到单个值,而 Lookup <TKey,TElement>将键映射到值集合.
我没有发现这种解释特别有用.Lookup用于什么?
我需要一个类似于Dictionary的对象,它可以使用相同的密钥存储多个条目.这可以作为标准集合,还是我需要自己动手?
为了澄清,我希望能够做到这样的事情:
var dict = new Dictionary<int, String>();
dict.Add(1, "first");
dict.Add(1, "second");
foreach(string x in dict[1])
{
Console.WriteLine(x);
}
Run Code Online (Sandbox Code Playgroud)
输出:
first
second
Run Code Online (Sandbox Code Playgroud) 如何在c#中的对象初始化程序例程中为属性声明一个新的查找类?
例如
new Component() { ID = 1, Name = "MOBO", Category = new Lookup<int, string> }
Run Code Online (Sandbox Code Playgroud)
类别位总是会出现编译错误.
我有一个叫做财产Category
是类型的Lookup<int, string>
,我想通过实例化这个属性
new Component() { ID = 1, Name = "MOBO", Category = new Lookup<int, string> };
Run Code Online (Sandbox Code Playgroud)
但我无法克服编译错误.
谁知道一个好的实现MultiValueDictionary
?基本上,我想要一些允许每个键有多个值的东西.我希望能够做类似的事情
dict.Add(key, val);
Run Code Online (Sandbox Code Playgroud)
如果密钥尚不存在,它将添加它,如果它存在,它将只添加该密钥的另一个值.我只是要迭代它,所以我真的不关心其他检索方法.
我想要一个Dictionary的功能,但我想为每个键存储多个值.如何在.NET/C#中完成?是否有支持此方案的内置集合?
如果我执行以下操作:
collection.Add("key1", new Order(1));
collection.Add("key1", new Order(2));
collection.Add("key1", new Order(3));
collection.Add("key2", new Order(4));
Run Code Online (Sandbox Code Playgroud)
然后运行以下应返回3个订单.
collection["key1"];
Run Code Online (Sandbox Code Playgroud)