4

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

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
user642378
  • 167
  • 6
  • 12
  • 2
    Do you *have* to use the old non-generic collections, or are you happy for us to propose solutions based on .NET 2 and higher? What about LINQ? – Jon Skeet Mar 08 '11 at 11:29

4 Answers4

7

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});
   }
}
Stecya
  • 22,896
  • 10
  • 72
  • 102
1

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.

grizzly
  • 1,146
  • 12
  • 26
0

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

d-live
  • 7,926
  • 3
  • 22
  • 16
0

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

Anuraj
  • 18,859
  • 7
  • 53
  • 79