Loop through Dictionary

  • A+
Category:Languages

I have a dictionary with a Person and a Count value:

Dictionary<string, int> PersonDictionary = new Dictionary<string, int>(); 

It has the following values:

Sally, 6 Beth, 5 Mary, 5 

I want to alternate each person and decrement the value by 1 each time it goes through the loop. I'm running into a real mind block on this one.

            string currentPerson = "";             foreach(KeyValuePair<string,int> owner in PersonDictionary)             {                 if(currentPerson == "" || currentPerson != owner.Key)                 {                     currentPerson = owner.Key;                     PersonDictionary[owner.Key] = owner.Value - 1;                 }                 else                 {                      continue;                 }             } 

The above DOESN'T work.

What is the best way to get Sally and decrement by 1 and then go to Beth and decrement by 1 and then go to Mary and decrement by 1 and then go back to Sally... So on and so forth.

Just add further clarification I want to loop through this and use the owner.Key value and pass that to another method. So I need to be able to loop through this dictionary 1 at a time.

 


Using Linq it would be as follows:

personDictionary = personDictionary.ToDictionary(e => e.Key, e => e.Value-1); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: