Hastable in C#: Using the same key multiple times

萝らか妹 提交于 2019-12-10 16:17:03

问题


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?

This is my code:

Hashtable localItemsIndex = new Hashtable();            
foreach (TzThing thing in localThingz)
         localItemsIndex.Add(thing.Id, thing); 

Thanks in advance jennie


回答1:


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



回答2:


The hashtable key must be unique: you can't add the same key twice into it. You may use List or HashSet where T is the key-value pair of your class (or use the .net KeyValuePair class) or the Dictionary class where V the list or set but you'll still need to manage the duplicate key insertion manually.




回答3:


If you have many things to go with the same key, put your things in a List.




回答4:


You cannot use HashTable for this. It only accepts unique keys. Otherwise you need to use List<T> with KeyValuePair<key,value> class.



来源:https://stackoverflow.com/questions/5231799/hastable-in-c-using-the-same-key-multiple-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!