Read Csv using LINQ

前端 未结 9 2121
无人及你
无人及你 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:15
    var stuff = from l in File.ReadAllLines(filename)
                let x = l.Split(new [] {',', ' '}, StringSplitOptions.RemoveEmptyEntries)
                         .Skip(1)
                         .Select(s => int.Parse(s))
                select new
                {
                    Sum = x.Sum(),
                    Average = x.Average()
                };
    

    If you're reading big files and memory use is a concern, then the following will work better using .NET 4:

    var stuff = from l in File.ReadLines(filename)
                let x = l.Split(new [] {',', ' '}, StringSplitOptions.RemoveEmptyEntries)
                         .Skip(1)
                         .Select(s => int.Parse(s))
                select new
                {
                    Sum = x.Sum(),
                    Average = x.Average()
                };
    

    In both cases, the stuff variable contains an enumerable which won't actually be executed until you start reading from it (e.g. inside a foreach loop).

    0 讨论(0)
  • 2020-12-01 05:22

    Hi you are looking for something like this

      var rows = new List<string> {"A, 22, 23, 12", "B, 32, 4, 33", "C, 34, 3 ,33"};
         foreach (var row in rows) {
                var sum = row.Split(',').Skip(1).Sum(x => Convert.ToInt32(x));
                var avg = row.Split(',').Skip(1).Average(x => Convert.ToInt32(x));
         }
    
    0 讨论(0)
  • 2020-12-01 05:23

    I just have discovered LinqToCsv library, it do all the parsing stuff and then you can query objects like collections and it supports deferred reading:

    http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library

    0 讨论(0)
提交回复
热议问题