How to get the key / value of a dictionary using 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 is not. So, how can I access the class that is contained in the value of my dictionary?

+3
source share
3 answers

The problem is that you rely on a non-generic interface IEnumeratorthat does not show the actual type of the element (its property Currenthas a type object). Use a common interface ( IEnumerator<T>which makes the element type easily detectable) and everything will be fine.

, - . Dictionary<,> IEnumerable. "" GetEnumerator , ( , ), .

, .

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

:

  • Dispose , using.
  • Reset . , .
  • , - - , . , , Value.
  • , foreach , .
+7
foreach(KeyValuePair<string, cAsso> kvp in mDico)
{
    // kvp.Key is string
    // kvp.Value is cAsso
}
+2
foreach (var kvp in mDico)
{
    var asso = kvp.Value;
    ...
}
0
source

Source: https://habr.com/ru/post/1792334/


All Articles