Нужна помощь с примером кода для суммирования значений столбца в текстовом файле с использованием C # в Visual studio
Скажем, текстовый файл имеет следующие строки
Хлеб, 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, извините за многие вопросы, ребята