2017-09-17 45 views
0

我在做一个简单的直线折旧应用程序。我的列表框显示年份和折旧金额。在同一个列表框中,我想添加一个“总计”并总结所有折旧。我添加了应用程序应该如何的图片。顺便说一句,我们需要使用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"))); 


    } 

Here is a picture of the app

+2

SO不是让人们为你做功课的地方。你做你认为是必需的,如果它不起作用,告诉我们你做了什么,并解释结果如何不符合你的需求。 – jmcilhinney

回答

0

这个怎么样?

double total = depreciationScheduleListBox.Items.Cast<string>().Select((string item) => Convert.ToDouble(System.Text.RegularExpressions.Regex.Match(item, "Depreciation: \\$(.+)").Groups[1].Value)).ToArray().Sum(); 

我将列表框的项目转换为IEnumerable。 然后,我得到了什么后Depreciation: $这应该是数字。 然后,我将这个字符串输出转换为Double,最终得到double[]然后得到它的总和

相关问题