2017-09-17 89 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[]然後得到它的總和

相關問題