Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate a hashtable for foreach in c#

Tags:

c#

I'm trying to enumerate a hashtable which is defined as:

private Hashtable keyPairs = new Hashtable();

foreach(SectionPair s in keyPairs)
{
   if(s.Section == incomingSectionNameVariable)
    {
      bExists = true;
      break;
    }
}
// more stuff here

But I get an error from Visual Studio 2013, "InvalidCastException was unhandled". Using a Dictionary, notwithstanding, I'm interested in knowing why I'm getting this error.

like image 444
Su Llewellyn Avatar asked Jan 05 '17 21:01

Su Llewellyn


1 Answers

As you can read in the Remarks section of the Hashtable class, the objects you enumerate are DictionaryEntrys. So you will have to rewrite it to something like:

foreach(DictionaryEntry s in keyPairs) {
   //Is Section the Key?
   if(s.Key == incomingSectionNameVariable) {
      bExists = true;
      break;
    }
}

A DictionaryEntry has a Key and Value element (that are of course the keys and the values in the Hashtable. Both are Objects since a Hashtable is not generic and thus the compiler can not know what the type of the Key and/or Value is.

I advice you however to use a Dictionary<TKey,TValue> since here you can specify the type of the Key and Value. In that case an example could look like:

private Dictionary<string,int> keyPairs = new Dictionary<string,int>();

foreach( KeyValuePair<string,int> kvp in keyPairs) {
    //do something with kvp
}

But here kvp.Key will be a string so you don't have to cast it and it is safer to use.

like image 76
Willem Van Onsem Avatar answered Oct 10 '22 00:10

Willem Van Onsem