Hastable in C #: using the same key multiple times

I am retrieving multiple records with the same identifier and I want to save them in a Hashtable in C #. I use 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 any way to solve this problem?

This is my code:

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

Thanks in advance Jennie

+4
source share
4 answers

Perhaps you should use Dictionary<Id,List<TzThing>> to store multiple values ​​for a single key

 public void Add(YourIdType key,TzThing thing ) { if(dictionary.ContainsKey(key)) { dictionary[key].Add(thing); } else { dictionary.Add(key,new List<TzThing> {thing}); } } 
+6
source

The hashtable key must be unique: you cannot add the same key to it twice. You can use List or HashSet, where T is the key-value pair of your class (or use the .net KeyValuePair class) or Dictionary, where V is a list or set, but you still need to control the double key insertion manually.

+1
source

If you have many things to go with the same key, put your things on the list.

0
source

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

0
source

Source: https://habr.com/ru/post/1342798/


All Articles