Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hastable in C#: Using the same key multiple times

Tags:

c#

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?

This is my code:

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

Thanks in advance jennie

like image 631
user642378 Avatar asked Feb 24 '23 21:02

user642378


2 Answers

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});
   }
}
like image 162
Stecya Avatar answered Mar 08 '23 08:03

Stecya


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.

like image 33
grizzly Avatar answered Mar 08 '23 06:03

grizzly