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
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});
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With