Reputation: 167
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
Upvotes: 4
Views: 8661
Reputation: 19608
You cannot use HashTable for this. It only accepts unique keys. Otherwise you need to use List<T>
with KeyValuePair<key,value>
class.
Upvotes: 0
Reputation: 23276
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});
}
}
Upvotes: 7
Reputation: 1156
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.
Upvotes: 1
Reputation: 8036
If you have many things to go with the same key, put your things in a List.
Upvotes: 0