在C#中测试for循环的最后一次迭代

时间:2018-07-23 07:11:37

标签: c#

   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;
    }

所以在这里,我正在遍历Dictionary<string,bool> upgradesPurchased,并试图确保for循环是否在由行if(i == upgradesPurchased.Count)标记的最后一次迭代中,我希望在其中发生什么在这种情况下,如果i等于字典中的项目数,则该字符串将在其末尾收到“ $”而不是“ |”但是似乎该行被完全忽略了

摘要:我需要测试for循环是否在最后一次迭代中,如果不是,则应将“ $”添加到字符串中。应该添加到字符串

3 个答案:

答案 0 :(得分:7)

循环条件为i < upgradesPurchased.Count,因此显然if (i == upgradesPurchased.Count)中的条件永远不会为真。

由于迭代是从零开始的,所以最后一次迭代将有i == upgradesPurchased.Count - 1

答案 1 :(得分:1)

所以您有这样的字典:

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

您有一个列表

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

您想获得

true|false|true$ 

这里存在一个模糊性(我们应该循环播放 的方式);但是主要原理是相同的:让.Net 为您完成工作String.Join)。如果您想遍历字典 (但是请注意,字典中的对没有任何顺序):

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

如果要遍历列表(您当前的代码):

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

答案 2 :(得分:0)

if(i == upgradesPurchased.Count - 1)