How do I get key/value of a Dictionnary with an Iterator?

//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?


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:

  • In general, you should Dispose of enumerators, typically with a using block.
  • The use of the Reset method on enumerators is not recommended. In fact, in this particular case, it is useless.
  • 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.
  • As Davide Piras points out, in most cases, you just want a normal foreach loop instead of messing around with the enumerator yourself.

  • foreach(KeyValuePair<string, cAsso> kvp in mDico)
    {
        // kvp.Key is string
        // kvp.Value is cAsso
    }
    

    foreach (var kvp in mDico)
    {
        var asso = kvp.Value;
        ...
    }
    
    链接地址: http://www.djcxy.com/p/30402.html

    上一篇: asp.net mvc将ViewBag字典显示为javascript

    下一篇: 如何用Iterator获得一个Dictionnary的键/值?