abc cba
abc cba

Reputation: 2633

Is that any Next function for a foreach in KeyValuePair?

Is that any Next function for a foreach in KeyValuePair ?

foreach (KeyValuePair<string, List<class>> KPV in dic )
{  }

or the only solution is using the traditional for loop with counter

Upvotes: 0

Views: 246

Answers (2)

Jon Limjap
Jon Limjap

Reputation: 95502

KeyValuePair<TKey, TValue> objects can be enumerated if they are inside a Dictionary<TKey, TValue> object.

Inside a Dictionary you can use the Dictionary.Enumerator structure, which exposes the Dictionary.Enumerator.MoveNext() method, which may be the "Next" function you are looking for.

It would be nice if you can tell us what you intend to do inside that foreach code block.

Upvotes: 1

horgh
horgh

Reputation: 18553

Read MSDN Dictionary Class:

Represents a collection of keys and values.

While iterating through the dictionary, you work with KeyValuePair Structure, which represents a pair of key (here string) and value (here List<T>). So if the intention is to loop through List<T> in each pair, you need to access KeyValuePair.Value Property:

foreach (KeyValuePair<string, List<object>> KPV in dic)
{
    foreach (object v in KPV.Value)
    {

    }
}

Also I replaced List<class> with List<object>, as definitely class is not a possible name for a type.

If each KeyValuePair.Key Property value is not important you may iterate through Dictionary.Values Property:

foreach (List<object> values in dic.Values)
{
    foreach (object v in values)
    {

    }
}

Upvotes: 3

Related Questions