Hashtable with ArrayList for value

S

Slickuser

Hi,
I am picking up C#.net and I'm trying to add many values to one single
key at different time in a loop.

If the key already exist, append new value to previous?
I'm not sure how to do that with ArrayList, any help? Thanks.

Hashtable data = new Hashtable();
if (!data.Contains(key))
{
data.Add(key, value);
}
else
{
//previous value already added
//want to add new value & keep previous value as well
}
 
S

Slickuser

Simply retrieve the ArrayList instance associated with the key, and add  
your new value to the list.  You only need to modify the ArrayList itself;  
the Hashtable already has the reference to that instance of ArrayList for 
that key, and so won't need to be updated in that scenario.

Can I see that in code example? Thanks.
 
S

Slickuser

Thanks a lot.

Simply retrieve the ArrayList instance associated with the key, and add  
your new value to the list. [...]
Can I see that in code example? Thanks.

What part do you need help with?  You simply need to make sure you're  
storing an ArrayList instance as the value for the Hashtable rather than  
the actual value.  Then just keep adding new values to the ArrayList as 
necessary.

The code, at its most basic, looks something like this:

         if (!data.Contains(key))
         {
             ArrayList list = new ArrayList();

             list.Add(value);

             data[key] = list;
         }
         else
         {
             data[key].Add(value);

data.Add(key, value);
 
S

Slickuser

Simply retrieve the ArrayList instance associated with the key, and add  
your new value to the list. [...]
Can I see that in code example? Thanks.

What part do you need help with?  You simply need to make sure you're  
storing an ArrayList instance as the value for the Hashtable rather than  
the actual value.  Then just keep adding new values to the ArrayList as 
necessary.

The code, at its most basic, looks something like this:

         if (!data.Contains(key))
         {
             ArrayList list = new ArrayList();
             list.Add(value);
             data[key] = list;

data.Add(key, value);
         }
         else
         {
             data[key].Add(value);

ArrayList list = new ArrayList();
list.Add(value);
data[key] = list;
//Doesn't this clear my previous values for that specific
key if I am doing in a while loop?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top