Read Csv using LINQ

前端 未结 9 2147
无人及你
无人及你 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 04:59

    using System.IO
    
    // turn file into IEnumerable (streaming works better for larger files)
    IEnumerable> GetTypedEnumerator(string FilePath){
      var File = File.OpenText(FilePath);
      while(!File.EndOfStream) 
          yield return new Tuple(
              Int.Parse(File[1]), 
              Int.Parse(File[2], 
              Int.Parse(File[3])
          );
       File.Close();
    }
    
    // this lines would return the sum and avg for each line
    var tot = GetTypeEnumerator(@"C:\file.csv").Select(l=>l.Item1 + l.Item2 + l.Item3);
    var avg = GetTypeEnumerator(@"C:\file.csv").Select(l=> (l.Item1 + l.Item2 + l.Item3) / 3);
    

    The streaming aporoach will let you handle laregr files because you wouldn;t need toload them into memeory first. Don't have VS here, haven't checked the syntax, might not compile as is.

    Regards GJ

    Damn, lot of answers already, need to type faster!

提交回复
热议问题