[英]How do I count data in a text file using c# with visual studio?
尋求示例代碼的幫助,以在 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
}
}
}
}
}
我需要找出如何對價格列中的所有值求和以寫入新文件,並將數量列上的值求和以寫入文件。 我知道如何遍歷每一行,但我們如何將每列的位置加在一起 0.O
正在想像 foreach 這樣的東西可能會起作用,對很多問題表示抱歉
你只需要一行一行地讀出文件。 嘗試這樣的事情:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.