user3504518
user3504518

Reputation: 1

I am trying to learn how to get the sum from a list of numbers in a file that represent currency in C#

I am trying to get the sum of a list of numbers from a file that represents currency amounts. I could not get it to work so I created an array inside my code and got it working for my assignment that way; but I still want to know how to program this myself for future reference. Here is a copy of the code that I did write and the values of the file Sales.txt are:

1245.67
1189.55
1098.72
1456.88
2109.34
1987.55
1872.36

Here is the copy of the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Lab7._2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // ReadScore method
        private void ReadSales(List<decimal> salesList)
        {
            try
            {
                // Open File Sales.txt
                StreamReader inputFile = File.OpenText("Sales.txt");

                // Read the sales into the list.
                while (!inputFile.EndOfStream)
                {
                    salesList.Add(decimal.Parse(inputFile.ReadLine()));
                }

                // Close the file
                inputFile.Close();
            }
            catch (Exception ex)
            {
                // Display an error message
                MessageBox.Show(ex.Message);
            }
        } 

        // DisplaySales method displaying to ListBox
        private void DisplaySales(List<decimal> salesList)
        {
            foreach (decimal sales in salesList)
            {
                runningTotalListBox.Items.Add(sales);
            }
        }
        // The average method returns the average of the values
        private double Average(List<decimal> salesList)
        {
            decimal total = 0;  //Accumulator
            double average; // to hold the average

            // Calculate the total of the sales
            foreach (decimal sales in salesList)
            {
                total += sales;
            }

            // Calculate the average of the scores.
            average = (double)total / salesList.Count;


            // Return average.
            return average;
        }




        private void calButton_Click(object sender, EventArgs e)
        {
            double averageSales; // To hold the average sales

            // Create a list to hold the sales
            List<decimal> salesList = new List<decimal>();

            // create decimal array
            double[] units = { 1245.67, 1189.55, 1098.72, 1456.88, 2109.34, 1987.55,        1872.36 };

            // Declair and initilize an accululator variable.
            double totals = 0;

            // Step through array adding each element
            for (int index = 0; index < units.Length; index++)
                {
                totals += units[index];
                }


            // Read the sales
            ReadSales(salesList);

            // Display Sales
            DisplaySales(salesList);

            // Display Total
            outputLabel.Text = totals.ToString();

            // Display Average Sales Cost
            averageSales = Average(salesList);
            averageCostLabel.Text = averageSales.ToString("n1");
        }







        private void button2_Click(object sender, EventArgs e)
        {
            // Close the window
            this.Close();
        }
    }
}

Upvotes: 0

Views: 89

Answers (2)

Racil Hilan
Racil Hilan

Reputation: 25341

You can use LINQ for that instead of the loop.

For sum:

decimal total = salesList.Sum()

For average:

decimal avg = salesList.Average();

Upvotes: 1

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12797

Simpler way to read all lines in bulk:

List<decimal> values = File.ReadAllLines("Sales.txt")
                           .Select(s => decimal.Parse(s, CultureInfo.InvariantCulture))
                           .ToList();

In your code:

private void ReadSales(List<decimal> salesList)
{
    salesList.AddRange(File.ReadAllLines("Sales.txt")
                           .Select(s => decimal.Parse(s, CultureInfo.InvariantCulture)));
}

Upvotes: 3

Related Questions