简体   繁体   中英

How to iterate through specific range of KeyValuePairs in a dictionary?

I have a dictionary with 4 KeyValuePair items in it. Now I'm having 2 foreach loops(loop 1 and loop 2), what I'm trying to achieve:

Loop1:

Loop through first 2 items using this foreachloop.

Loop2:

Loop through items 3-4 using this foreachloop.

I'm not sure if this is possible therefore I've tried this instead:

@for (int DictItem = 0; i < finalDictionary.Count; DictItem++)
{
   var test = finalDictionary[i];
   if(test == 1 || test == 2)
   { 
          //First 2 items
   }

  if(test == 3 || test == 4)
  { 
          //3th and 4th items
  }
}

Here I'm trying to obtain the KeyValuePair by index of the for loop, however this does not work.

Thanks in advance

Dictionaries in .NET (ie implementations of IDictionary<TKey,TValue> ) do not have any defined order of key/value-pairs.

However, if your keys are sortable (and they implement IComparable<TKey> ) then you can do this:

Dictionary<TKey,TValue> dict = ...
List<TKey> sortedKeys = dict.Keys.OrderBy( k => k ).ToList();

foreach( TKey key in sortedKeys.Take(2) ) {
    TValue value = dict[key];

    Console.WriteLine( value );
}

foreach( TKey key in sortedKeys.Skip(2).Take(2) ) {
    TValue value = dict[key];

    Console.WriteLine( value );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM