generic reset of values for hashtable

  • Thread starter Thread starter Guest
  • Start date Start date
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 ?
 
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
 
Thanks !!! - I dont know hoe long it would have taken me to think of that !
It works perfectly.
 
Back
Top