• 0

Need help summing-up list of decimals


Question

Hi,

 

I have tried for days, and I cannot find a solution that explains/fits into the mess I have committed myself to.

 

VS 2017     C#.NET.

 

I have a textBox (entryBox) which feeds a prefix and a decimal into a listBox (list1), one pair at each button.Click. A foreach()-statement separates prefix and decimal, and saves decimal to a decimal-list (plaAmounts).

 

I wish to add up all decimals on that list, but cannot find a working way to do so. All my last textBox displays, is the most recently added decimal. Any suggestions?

 

 

class

{

      private void buttonClick

      {    

            list1.Items.Add(entryBox.Text);
           

            for (int i = 0; i < list1.Items.Count; i++)
            {
            .    string itemText = list1.Items.ToString();               
            .    var plaAmounts = new List<decimal>();                
            .   
            .    if (itemText.Contains("pla"))
            .    {
            .    .    list1.SetSelected(i, true);                    
            .    .    foreach (Object selecteditem in list1.SelectedItems)
            .    .    {                        
            .    .    .   string[] substrings = itemText.Split(',');
            .    .    .   string plaNumberText = substrings[1];
            .    .    .   decimal plaNumber = Convert.ToDecimal(plaNumberText);

            .    .    .   plaAmounts.Add(plaNumber);
            .    .    }
            .    }

            .    decimal plaTotals = plaAmounts.Sum();
            .    plaBox.Clear();
            .    plaBox.AppendText(plaTotals.ToString());

            }

      }

}

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

This is your algorithm:

for each item in list1:
     create a list of decimals
     parse the item as a decimal, add it to the new list
     sum up the values in that new list
     update the text box with that sum

Can you figure out why this isn't doing what you want?

 

(Hint 1: the list of decimals you create will only ever contain one item).

(Hint 2: why would you need to update the text box once for every item in the list?)

 

This is probably what you wanted to do:

create a list of decimals
for each item in list1:
     parse the item as a decimal, add it to the new list

sum up the values in that new list
update the text box with that sum

 

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.