How can I add the value of an item in a list box to a local variable in C#?

174 Views Asked by At

So I'm doing a practical that involves asking the user to input a score between 0 and 100. The program will keep track of the number of scores that have been entered, the total score (sum of all scores) and the average score.

To calculate the total score, I've come up of the idea of using a for loop that will cycle through my listbox and add each score to a variable (below).

int sTotal = 0;
for(int i = 0; i < lstScores.Items.Count; i++)
{
    //Calculation occurs here
}
txtScoreTotal.Text = Convert.ToString(sTotal);

Thing is, I don't exactly know how to do it. I've tried searching to no avail. Any help would be greatly appreciated.

3

There are 3 best solutions below

5
Siccio On BEST ANSWER
    int sTotal = 0;
    int Average = 0;
    for(int i = 0; i < lstScores.Items.Count; i++)
    {
         bool result = Int16.TryParse(lstScores.Items[i],out int res);
         if (result)
         {
            sTotale += res;        
         }
    }
    Average = sTotal / lstScores.Items.Count;
    txtScoreTotal.Text = Convert.ToString(sTotal);
3
D.J. Klomp On

Easiest is it to do with a foreach loop like this:

        int sTotal = 0;
        foreach (string item in lstScores.Items)
        {
            sTotal += Int32.Parse(item);
        }
        txtScoreTotal.Text = Convert.ToString(sTotal);
0
SSD On

See this

int i = 0, result = 0;
while (i < lstScores.Items.Count)
{
   result += Convert.ToInt32(lstScores.Items[i++]);
}

txtScoreTotal.Text = Convert.ToString(result);

I havent tried following, but you can try 1 line solution too

var sum = lstScores.Items.OfType<object>().Sum(x => Convert.ToInt32(x));

You need to handle exception if sum exceedes int.Max