3
//mDIco is a Dictionnary with string as keys and homemade class (cAsso) as values
IEnumerator iterdico = mDico.GetEnumerator();

iterdico.Reset();

while (iterdico.MoveNext())
{
    var asso = iterdico.Current as cAsso;
    if (asso != null)
    {
        //Code
    }
}

I thought this would work, but obviously it doesnt. So how I do i get access to the class which is contained into the value of my dictionnary?

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
Wildhorn
  • 926
  • 1
  • 11
  • 30

3 Answers3

8

The problem is that you are relying on the non-generic IEnumerator interface, which doesn't reveal the real element-type (its Current property is of type object). Use the generic interface (IEnumerator<T>, which does make the element-type easily discoverable) instead, and you will be fine.

Of course, you don't need any special effort for this. The Dictionary<,> class implements the IEnumerable interface explicitly. Its 'implicit' GetEnumerator method returns an enumerator that is strongly typed (a nested type that implements the generic interface), which is what we want.

So it's fine to use implicit typing all the way and let the compiler figure things out.

// Actually a Dictionary<string, cAsso>.Enumerator
// which in turn is an IEnumerator<KeyValuePair<string, cAsso>>
using(var iterdico = mDico.GetEnumerator())
{
   while (iterdico.MoveNext())
   {
       // var = KeyValuePair<string, cAsso>
       var kvp = iterdico.Current;

       // var = string
       var key = kvp.Key;

       // var = cAsso
       var value = kvp.Value;
       ...
   }
}

EDIT:

A few other peripheral points:

  1. In general, you should Dispose of enumerators, typically with a using block.
  2. The use of the Reset method on enumerators is not recommended. In fact, in this particular case, it is useless.
  3. Note that the element-type of the dictionary's enumerator is a Key-Value pair, not the value itself. if you are only interested in the values, enumerate the sequence returned by the dictionary's Value property.
  4. As Davide Piras points out, in most cases, you just want a normal foreach loop instead of messing around with the enumerator yourself.
Ani
  • 111,048
  • 26
  • 262
  • 307
  • @David Yaw: Yes, so? As you can see, I'm getting the key and value out from the KVPs separately. – Ani Feb 15 '11 at 20:58
  • Thanks alot, it is all the infos I needed. – Wildhorn Feb 15 '11 at 21:24
  • I am surprised that this answer has very few upvotes though it gives a very balanced and type safe way of handling this as compared to [this answer on another SO thread](http://stackoverflow.com/a/141098/365188). – Ozair Kafray Jan 05 '16 at 07:35
2
foreach(KeyValuePair<string, cAsso> kvp in mDico)
{
    // kvp.Key is string
    // kvp.Value is cAsso
}
David Yaw
  • 27,383
  • 4
  • 60
  • 93
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
0
foreach (var kvp in mDico)
{
    var asso = kvp.Value;
    ...
}
n8wrl
  • 19,439
  • 4
  • 63
  • 103