generic reset of values for hashtable

G

Guest

I have a reason to resuse hashtables and I'd like to set the values to null
without having to reload the keys.- > which is what the clear method does.

If I try a foreach construct I get an error that I cannot alter the value.
The documentation for using an enumerator and moveNext also have the same
restriction.

WONT WORK:
private Hashtable hashValueNuller(Hashtable theHash)
{
foreach (DictionaryEntry dObj in theHash)
{
dObj.Value = null;
}
return theHash;
}

Is the only way out of this to use a clear and constructor takling an array
of keys ?
 
J

Jay B. Harlow [MVP - Outlook]

Andrew,
Have you tried to use a foreach over the keys of the Hashtable?

Something like:

static private Hashtable hashValueNuller(Hashtable theHash)
{
object[] keys = new object[theHash.Keys.Count];
theHash.Keys.CopyTo(keys, 0);
foreach (object key in keys)
{
theHash[key] = null;
}
return theHash;
}

Note a copy of the keys is made, as changing a key's value is considered a
change to the Hashtable.

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net


|I have a reason to resuse hashtables and I'd like to set the values to null
| without having to reload the keys.- > which is what the clear method does.
|
| If I try a foreach construct I get an error that I cannot alter the
value.
| The documentation for using an enumerator and moveNext also have the same
| restriction.
|
| WONT WORK:
| private Hashtable hashValueNuller(Hashtable theHash)
| {
| foreach (DictionaryEntry dObj in theHash)
| {
| dObj.Value = null;
| }
| return theHash;
| }
|
| Is the only way out of this to use a clear and constructor takling an
array
| of keys ?
|
| --
| Andrew
 
G

Guest

Thanks !!! - I dont know hoe long it would have taken me to think of that !
It works perfectly.
 

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