Iterating thru a Generic Dictionary

  • Thread starter Thread starter Charles Jenkins
  • Start date Start date
C

Charles Jenkins

What is the right way to iterate through elements stored in a
System.Collections.Generic.Dictionary?

I have these aliases:

namespace Ui
{
using KeyDefinitionList =
System.Collections.Generic.Dictionary<string, KeyDefinition>;
using KeyDefinitionListEntry =
System.Collections.Generic.KeyValuePair<string, KeyDefinition>;

...
}

A KeyPanel.Group contains a KeyDefinitionList (dictionary), which of
course contains KeyDefinitions. The KeyPanel.Group code also defines
this method:

public IEnumerator GetEnumerator() {
// Expose KeyDefinitionList.GetEnumerator()
return m_definitions.GetEnumerator();
}

All I want to do in my function is examine every KeyDefinition in the
list. Sounds easy, right? Here's the code:

public void enableGroup( string name ) {

KeyPanel.Group group = m_groups[ name ];

foreach ( KeyDefinitionListEntry entry in groups ) {
KeyDefinition definition = entry.Value;
if ( definition != null ) {
enableKey( definition );
}
}
}

It works fine on the PC, but when I run it in the Windows CE emulator
or on my Windows CE device, the foreach line causes an 'invalid case'
exception. It seems as if the Compact Framework's version of the
generic dictionary does not return a strongly typed KeyValuePair.

Can anyone point me to a tutorial on how to successfully iterate
through a dictionary in the Compact Framework?

Thanks!
 
... when I run it in the Windows CE emulator or on my Windows CE
device, the foreach line causes an 'invalid case' exception.

BTW, this is a typo. The exception is actually an 'invalid cast' exception.
 
Back
Top