Hastable在C#:使用相同的密钥多次 [英] Hastable in C#: Using the same key multiple times
本文介绍了Hastable在C#:使用相同的密钥多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我取具有相同ID的多个记录,我想将它们存储在的Hashtable
在C#。我使用的ID作为的Hashtable
键,值是对象本身。它抛出一个异常,因为相同的密钥再次添加。有没有办法解决这个问题?
I fetch multiple records with the same id and I want to store them in a Hashtable
in C#. I'm using the id as the key in the Hashtable
, and the value is the object itself. It throws an exception because the same key is added again. Is there a way to fix this problem?
这是我的代码:
Hashtable localItemsIndex = new Hashtable();
foreach (TzThing thing in localThingz)
localItemsIndex.Add(thing.Id, thing);
在此先感谢
珍妮
Thanks in advance jennie
推荐答案
也许你应该使用词典< ID,列表< TzThing>>
来存储多个值一键
Maybe you should use Dictionary<Id,List<TzThing>>
to store multiple values for one key
public void Add(YourIdType key,TzThing thing )
{
if(dictionary.ContainsKey(key))
{
dictionary[key].Add(thing);
}
else
{
dictionary.Add(key,new List<TzThing> {thing});
}
}
这篇关于Hastable在C#:使用相同的密钥多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文