下面的代码执行我想要的,除了它太硬编码的事实,并将显示值为0的构造材料.现在它可能会显示
木材:100%,砌体:0%,混凝土:0%,钢:0%,轻金属:0%,移动房屋:0%,其他:0%,未知:0%
我想在那种情况下显示它
木材:100%
我是一个极端的amatuer,我知道如何做到这一点的唯一方法是10000 IF语句,但必须有一个更优雅的方式.convertFIRE函数是这些主要构造"桶"的映射
for (int row = firstrow + 1; row <= sheet5.LastRowNum; row++) { convertFIRE(sheet5.GetRow(row).GetCell(1).ToString()); if (constructioncode == "Wood") { wood = wood + sheet5.GetRow(row).GetCell(10).NumericCellValue; } else if (constructioncode == "Masonry") { masonry = masonry + sheet5.GetRow(row).GetCell(10).NumericCellValue; } else if (constructioncode == "Concrete") { concrete = concrete + sheet5.GetRow(row).GetCell(10).NumericCellValue; } else if (constructioncode == "Steel") { steel = steel + sheet5.GetRow(row).GetCell(10).NumericCellValue; } else if (constructioncode == "Light Metal") { lghtmetal = lghtmetal + sheet5.GetRow(row).GetCell(10).NumericCellValue; } else if (constructioncode == "Mobile Home") { mobilehome = mobilehome + sheet5.GetRow(row).GetCell(10).NumericCellValue; } else if (constructioncode == "Other") { other = other + sheet5.GetRow(row).GetCell(10).NumericCellValue; } else if (constructioncode == "Unknown") { unknowncode = unknowncode + sheet5.GetRow(row).GetCell(10).NumericCellValue; } } constructiontext = "Wood: " + String.Format("{0:P1}", wood) + ", " + "Masonry: " + String.Format("{0:P1}", masonry) + ", " + "Concrete: " + String.Format("{0:P1}", concrete) + ", " + "Steel: " + String.Format("{0:P1}", steel) + ", " + "Light Metal: " + String.Format("{0:P1}", lghtmetal) + ", " + "Mobile Home: " + String.Format("{0:P1}", mobilehome) + ", " + "Other: " + String.Format("{0:P1}.", other) + ", " + "Unknown: " + String.Format("{0:P1}", unknowncode);
D Stanley.. 5
因此,您有几个变量可以根据键字符串跟踪数字.而不是几个变量,你可以使用Dictionary
:
Dictionarypercentages = new Dictionary (); for (int row = firstrow + 1; row <= sheet5.LastRowNum; row++) { convertFIRE(sheet5.GetRow(row).GetCell(1).ToString()); string key = constructioncode; decimal value = sheet5.GetRow(row).GetCell(10).NumericCellValue; if(percentages.ContainsKey(key); // does the key already exist? percentages[key] += value; // add to the value else // else percentages[key] = value; // add the key and value to the dictionary
然后,您可以循环键值对,只有在值存在和/或大于0时才输出键和值.
因此,您有几个变量可以根据键字符串跟踪数字.而不是几个变量,你可以使用Dictionary
:
Dictionarypercentages = new Dictionary (); for (int row = firstrow + 1; row <= sheet5.LastRowNum; row++) { convertFIRE(sheet5.GetRow(row).GetCell(1).ToString()); string key = constructioncode; decimal value = sheet5.GetRow(row).GetCell(10).NumericCellValue; if(percentages.ContainsKey(key); // does the key already exist? percentages[key] += value; // add to the value else // else percentages[key] = value; // add the key and value to the dictionary
然后,您可以循环键值对,只有在值存在和/或大于0时才输出键和值.