如何使用带Visual Studio的c#计算文本文件中的数据?

问题描述 投票:-2回答:1

寻找有关示例代码的帮助,以便在Visual Studio中使用C#对文本文件中的列值求和

假设文本文件包含以下行

面包,2(价格),3(量) 奶酪,5,1 牛奶,1,2- Weetbix,1,5

这是我到目前为止,但不知道如何做到这一点,它是一个.txt文件

public class GroceryProgram
{
    static void Main(string[] args)
    {
        // main consists of a single call to the grocery class
        var grocery = new InvoiceItem();
       // grocery.readFile();
        grocery.writeFile();
    }

    public class InvoiceItem
    {   //label all properties
        public static List<string> items = new List<string>();

        public string type { get; set; }
        public string name { get; set; }
        public double price { get; set; }
        public double quantity { get; set; }
        public double weight { get; set; }

        public InvoiceItem()
        {
        }
        public InvoiceItem(string n, double p) //declaring the main input to be a string name of grocery n followed by a double as p
        {
            name = n;
            price = p;
        }
        public List<string> readFile()
        {
            string line = "";
            StreamReader reader = new StreamReader("groceries.txt"); //variable reader to read file
            while ((line = reader.ReadLine()) != null) //reader reads each line while the lines is not blank, line is assigned value of reader
            {
                line = line.Trim();     //gets rid of any spaces on each iteration within the line

                if (line.Length > 0) //during  each line the below actions are performed
                {
                    string[] splitArray = line.Split(new char[] { ',' });  //creates a array called splitArray which splits each line into an array and a new char

                    type = splitArray[0]; // type is assigned for each line at position [0] on
                    name = splitArray[1]; //name is assigned at position [1]

                    //<<<-------food cost calculation methods initialized-------->>>>
                    RegularItem purchasedItem = new RegularItem(splitArray); //purchased Item is the each line to be printed
                    FreshItem freshItem = new FreshItem(splitArray);

                    double regCost = purchasedItem.getRegularCost();  //regCost will multiply array at position [2] with [3]
                    double freshCost = freshItem.getFreshItemCost();

                    string regArr = string.Join(",", line, "Cost: ", regCost);
                    string freshArr = string.Join(",", line, "Cost: ", freshCost);

                    if (type == "regular")
                    {
                        // items.InsertRange(4, (arrayList)); //first write a line in the list with the each line written
                        items.Add(regArr);
                        //items.Add(Convert.ToString(newArray));
                        //items.Add("RegularItemCost:");
                        //items.Add(Convert.ToString(regCost));  //next add the regCost method to write a line with the cost of that item
                    }
                    else if (type == "fresh")
                    {
                        items.Add(freshArr);
                        //items.Add(Convert.ToString(freshItem)); //first write a line in the list with the each line written
                        //items.Add("FreshItemCost:");
                        //items.Add(Convert.ToString(freshCost));  //next add the fresh method to write another line with the cost of that item
                    }

                }


            }

            return items;
        }

        public int sumPrice(string filepath)
        {
            using (StreamReader readAgain = new StreamReader("groceries.txt"))
            {
                int i = 0;
                while (readAgain.ReadLine() != null) { i++; }
                return i;
            }
        }


        // WRITE FILE
        public void writeFile() //maybe add file name inside paranthesis <<+=========MAIN EXECUTOR
        {
            //Begin writing
            List<string> lines = readFile();

            string[] first = { "Grocery for you", Convert.ToString(DateTime.Now) };
            StreamWriter file = new StreamWriter("c:\\MicrosoftVisual\\invoice.txt");  //sets to use variable file to write to location

            foreach (string firstLine in first)
            {
                file.WriteLine(firstLine);   //use file to write the header grocery for you first
            }
            //begin writing all items into the file
            foreach (string newLine in lines)
            {
                file.WriteLine(newLine);   //use file to write all lines
                Console.WriteLine(newLine);
            }

            //  file.WriteLine(items[2].Sum); //trying to get total price by adding position 2 for total weight for later
            //file.WriteLine(items[3].Sum); //trying to get total quantity/weight
            file.Flush();
        }


        public class RegularItem : InvoiceItem //inheriting properties from class GroceryItem
        {

            private string[] splitArray;

            public RegularItem()
            {
            }

            public RegularItem(string[] splitArray) //enables constructor for RegularItem to split into array
            {
                this.type = splitArray[0];
                this.name = splitArray[1];
                this.price = double.Parse(splitArray[2]); //each line at position 4 is a double
               this.quantity = double.Parse(splitArray[3]); //each line at position 3 is parsed to an integer
            }

            public double getRegularCost() //method from cost of regular
            {
                return this.price * this.quantity * 1.1; //workout out cost  for purchases including GST
            }
        }
        public class FreshItem : InvoiceItem    //Inheriting properties from class Purchased Item
        {
            public double weight;
            private string[] splitArray;

            public FreshItem()
            {
                this.type = splitArray[0];
                this.name = splitArray[1];
                this.price = double.Parse(splitArray[2]); //each line at position 4 is a double
                this.weight = double.Parse(splitArray[3]); //each line at position 3 is parsed to an integer

            }
            public FreshItem(string[] splitArray) //enables constructor for RegularItem to split into array
            {
                this.type = splitArray[0];
                this.name = splitArray[1];
                this.price = double.Parse(splitArray[2]); //each line at position 4 is a double
                this.weight = double.Parse(splitArray[3]); //each line at position 3 is parsed to an integer
            }
            public double getFreshItemCost() //method to get cost of fresh item
            {
                return this.price * this.weight; //workout cost of the fresh item excluding GST
            }
        }
    }
}

}

我需要找出如何将price列中的所有值相加以写入新文件,并将quantity列上的值相加以写入文件。我知道如何遍历每一行,但我们如何将每列的位置加在一起0.O

想到也许像foreach这样的东西可能有用,抱歉很多问题的人

c# visual-studio
1个回答
1
投票

你只需要逐行读出文件。尝试这样的事情:

    decimal totalPrice = 0;
    StreamReader reader = new StreamReader("your file fullpath");
    while(!reader.EndOfStream)
    {
        decimal price = 0;
        decimal.TryParse(reader.ReadLine().Split(',')[1], out price);

        totalPrice += price;
    }
    reader.Close();
© www.soinside.com 2019 - 2024. All rights reserved.