[英]How do I add all the items in my list box and show “total” in the same list box
我正在做一个简单的直线折旧应用程序。 我的列表框显示了年份和折旧金额。 在同一列表框中,我想添加一个“总计”并汇总所有折旧。 我添加了一张有关应用程序外观的图片。 顺便说一句,我们需要使用FOR循环。
private void calcButton_Click_1(object sender, EventArgs e)
{
//Declare Vairables
double cost, salvage, depreciation;
int usefulLife;
int total = 0;
//grab data
double.TryParse(assetCostTextBox.Text, out cost);
double.TryParse(salvageValueTextBox.Text, out salvage);
int.TryParse(usefulLifeNumericUpDown.Text, out usefulLife);
//Print heading
string formatCode = "{0,7}{1,20}";
depreciationScheduleListBox.Items.Add(string.Format(formatCode,
"Years:", "Depreciation:"));
depreciationScheduleListBox.Items.Add("");
//use for loop to calculate deprecation value of each year
int iterations = 0;
for (iterations = 1; iterations <= usefulLife; iterations += 1)
{
depreciation = (cost - salvage) * 1/usefulLife;
depreciationScheduleListBox.Items.Add(string.Format(formatCode,
iterations, depreciation.ToString("C2")));
}
这个怎么样 ?
double total = depreciationScheduleListBox.Items.Cast<string>().Select((string item) => Convert.ToDouble(System.Text.RegularExpressions.Regex.Match(item, "Depreciation: \\$(.+)").Groups[1].Value)).ToArray().Sum();
我将您的listBox的项目转换为IEnumerable。 然后,我在Depreciation: $
后得到了什么Depreciation: $
应该是数字。 然后,我将此字符串输出转换为Double并得到最终的double[]
然后求和
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.