C# Hashtable create, add, update, remove and removed problem in a loop

Lionsure 2020-07-23 Original by the website

Hashtable is a container for temporarily storing data. It facilitates the key/value to quickly access data. Key is the key used to quickly find data, and value is the value stored in the key. The namespace is System.Collections, so don't forget to use it before using.

 

1. C# create Hashtable

Hashtable ht = new Hashtable();

If you want to synchronize like this:

Hashtable ht = Hashtable.Synchronized(new Hashtable());

 

2. C# Hashtable add

ht.Add("01", "userName1");
       ht.Add("02", "userName2");
       ht.Add("03", "userName3");

Or(when the added value is regular)

for(int i = 0; i < 10; i++)
              ht.Add(i, i);

 

3. C# update Hashtable value

ht["01"] = "user1";
       ht["02"] = "user2";
       ht["03"] = "user3";

 

4. C# remove Hashtable item

1) Remove item by the specified key

ht.Remove("01");
       ht.Remove("02");
       ht.Remove("03");

 

2) Remove all items

ht.Clear();

 

5. Removed problem in a loop

When traversing the Hashtable, you cannot remove it while traversing, otherwise an error will occur. Examples are as follows:

for(DictionaryEntry de in ht)
       {
              if(condition)
                     ht.Remove(de.Key);
       }

As in the previous example, if a certain condition is met in a loop, the element is deleted. Such traversal will be abnormal, because the total number of Hashtable(that is, Count) changes during the traversal process, and the loop will be abnormal.

You may ask, if you can't delete an element that meets a certain condition like this, how can you delete it?

The method is also very simple. You can temporarily store the key to be deleted in another Hashtable, then traverse the Hashtable with the key temporarily stored, and delete the elements that meet the conditions.