Home > Software design >  Using dictionary for sum of values from a text file from multiple rows and columns
Using dictionary for sum of values from a text file from multiple rows and columns

Time:06-27

I have text data in format of:

OrderID:100,ItemID:1,Price:1000 //Row1
OrderID:101,ItemID:2,Price:200  //Row2
OrderID:102,ItemID:3,Price:100  //Row3

I need the Totalitems:4 and totalPrice:1300 and I don't know which way to get an output for this problem using Indexof to access or something else

Any help is appreciated.

CodePudding user response:

One way is to first read all the lines from the file with File.ReadAllLines(fileName). Then you can loop through the lines and parse out and aggregate the information you need.

var lines = File.ReadAllLines(fileName);

int totalItems = 0;
decimal totalPrice = 0;

foreach (var line in lines)
{
    var columns = line.Split(',');
    var priceColumn = columns[2];
    var price = decimal.Parse(priceColumn.Split(':')[1]);

    totalItems  ;
    totalPrice  = price;
}

Console.WriteLine($"Total items: {totalItems}");
Console.WriteLine($"Total price: {totalPrice}");

For more complex CSV files or more advanced features, you can look at CsvHelper, which has worked well for me.

CodePudding user response:

// parse the price
const string sep = ",Price:";    

// initial tuple for sum&count, aka "seed"            
(decimal sum, int count) = (0,0); 

var lines  = File.ReadAllLines(someCsvFilePath);
var result = lines.Aggregate((sum, count),
        (curr, line) => line?.IndexOf(sep) is {} pos and > -1
                     && decimal.TryParse(line.Substring(pos   sep.Length), out var prc)
                      ? (curr.sum   prc, curr.count   1) : curr);

Console.WriteLine("Sum: {0:N0}, TotalItems: {1:N0}", result.sum, result.count);
  •  Tags:  
  • c#
  • Related