How to skip some empty rows in csv file and continue reading rows with data? c# console application

后端 未结 2 1244
生来不讨喜
生来不讨喜 2021-01-16 00:26

I do have have 5 column within my CVS file, the first two columns have 3 empty rows. I would like to skip these empty rows. I know that I have to loop through the file howev

2条回答
  •  暖寄归人
    2021-01-16 01:20

    If you are not familiar/comfortable with Linq then another aproach is like this.

    public static IList ReadFile(string fileName)
    {
      var results = new List();
      string[] target = File.ReadAllLines(fileName);
      foreach (string line in target)
      {
        var array = line.Split(','); //If your csv is seperated by ; then replace the , with a ;
        if (!string.IsNullOrWhiteSpace(array[0]) && !string.IsNullOrWhiteSpace(array[1]) && array.Length >= 2)
        results.Add(line);
      }
    return results;
    }
    

    target can still be defined as var, but I've defined it as string[] to make it more obvious that you can then do foreach over the array.

    However I like Gilad Green's solution using Linq. I'm less familiar with it so it's not the first solution I think of, but I think it's worth getting familiar with.

提交回复
热议问题