N
N
new-profile-web2020-03-04 23:26:58
csv
new-profile-web, 2020-03-04 23:26:58

Grouping and Summing values ​​from CSV file using Linq C#?

I am a beginner and trying to figure out the task, there is a CSV file that contains data in one column , example:
03 /03/
2020,100 03/04/2020,150 04/09/ 2020,130 04/10/
2020,150 Note: DateTime, Value



You need to group the data for 1 month (sum up their values) and get the average value for the month (for example, there are 4-5 sales in a month, here you need the sum per month / for the number of values ​​in the same month)


Result:
03.2020.130
04.2020.140

Action:
var result = lstTest
  .Select(row => row.Split(','))
  .GroupBy(row => DateTime.Parse(row[0]), row => int.Parse(row[1]), (date, val) => new { Date = date, Value = val }) //.Average()
  .GroupBy(x => x.Date.Month, x => x.Value.Average());


I get a response:
System.Linq.Lookup`2+Grouping[System.Int32,System.Double]

Old version of the code:
spoiler

List lstTest = new List(); //перебрасываю значения во временный список

for(int i = 3; i < lst.Count; i++)
lstTest.Add(lst[i]);

var result =
from line in lstTest
let values = line.Split(',')
let date = values[0]
group values by date into g
orderby g.Key
select new
{
date_column = g.Key,
value_column = g.Sum(x => int.Parse(x[1]))
};

var result2 = result.Select(record => record.date_column + "," + record.value_column);

foreach(var r in result2)
Console.WriteLine(r);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2020-03-05
@freeExec

var avg = lstTest
  .Select(row => row.Split(','))
  .GroupBy(row => row[0].Substring(3), row => int.Parse(row[1]), (date, val) => new { Date = date, Value = val.Average() });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question