Read Csv using LINQ

前端 未结 9 2153
无人及你
无人及你 2020-12-01 04:55

I am having a csv file like this

A, 22, 23, 12
B, 32, 4, 33
C, 34, 3 ,33

I want to print the sum and average of each row and skip the first

9条回答
  •  隐瞒了意图╮
    2020-12-01 05:05

    Something like this maybe:

    var csv = @"A, 22, 23, 12
    B, 32, 4, 33
    C, 34, 3 ,33";
    
    var lines =
        csv.Split('\n').Select(x => x.Split(',').Skip(1).Select(n => int.Parse(n))).Select(x => new {Sum = x.Sum(), Average = x.Average()});
    foreach (var line in lines)
    {
        Console.WriteLine("Sum: " + line.Sum);
        Console.WriteLine("Average: " + line.Average);
    }
    

    In general, I don't suggest to do something like this. You should use a full blown CSV reader to parse the CSV file and you should include error handling.

提交回复
热议问题