1
   public string GetUpgradesPurchasedVal()
   {
        string upgradesPurchasedVals = "";
        for (int i = 0; i < upgradesPurchased.Count; i++) {
            if (i == upgradesPurchased.Count) {
                upgradesPurchasedVals += upgradesPurchased [upgradeNames[i]].ToString () + "$";
            } else {
                upgradesPurchasedVals += upgradesPurchased [upgradeNames[i]].ToString () + "|";
            }
        }
        return upgradesPurchasedVals;
    }

So here I am looping through the Dictionary<string,bool> upgradesPurchased and I am trying to make sure if the for loop is at the last iteration marked by the line if(i == upgradesPurchased.Count) what I expected to happen in this case is if i is equal to the number of items in the dictionary then the string would receive a "$" at the end of it instead of a "|" however it would seem that the line is ignored altogether

Summary: I need to test if the for loop is at the last iteration if so then "$" should be added to the string if not "|" should be added to the string

Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17

3 Answers3

8

The loop condition is i < upgradesPurchased.Count, so clearly the condition in if (i == upgradesPurchased.Count) can never be true.

Since the iteration is zero-based, the last iteration would have i == upgradesPurchased.Count - 1.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
2
if(i == upgradesPurchased.Count - 1)
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
1

So you have a dictionary like this:

 Dictionary<string, bool> upgradesPurchased = new Dictionary<string, bool>() {
   {"Pentium 3", true},
   {"Core i9",   false},
   {"Abacus",    true},
 };

and you have a list

List<string> upgradeNames = new List<string>() {
  {"Pentium 3", "Core i9", "Abacus"},
};

And you want to obtain

true|false|true$ 

Here there's an ambiguity (what and how should we loop); however the main principle is the same: let .Net do the work for you (String.Join). In case you want to loop over the dictionary (but, please, notice that pairs in the dictionary don't have any order):

public string GetUpgradesPurchasedVal() {  
  return !upgradesPurchased.Any() 
    ? ""
    : string.Join("|", upgradesPurchased.Select(pair => pair.Value)) + "$";
}

In case you want to loop over the list (your current code):

public string GetUpgradesPurchasedVal() {  
  return !upgradesPurchased.Any() 
    ? ""
    : string.Join("|", upgradeNames.Select(name => upgradesPurchased[name])) + "$";
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215