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

后端 未结 2 1241
生来不讨喜
生来不讨喜 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:13

    Use a Where clause to keep only rows that are not NullOrWhiteSpace (null, empty or only white spaces):

    public static IList<string> ReadFile(string fileName)
    {
        return File.ReadAllLines(fileName)
                   .Where(line => !string.IsNullOrWhiteSpace(line))
                   .ToList();
    }
    

    After better understanding what you are after for then: For each line use Split to get the different columns and then check that the first 2 are not empty:

    public static IList<string> ReadFile(string fileName)
    {
        return (from line in File.ReadAllLines(fileName)
                where !string.IsNullOrWhiteSpace(line)
                let columns = line.Split(',')
                where columns.Length >= 2 && 
                    !string.IsNullOrWhiteSpace(columns[0]) &&
                    !string.IsNullOrWhiteSpace(columns[1])
                select line).ToList();
    }
    

    Changed to syntax query just because in my opinion it is cleaer when we start needing things like let


    If what you want is get all the column values from the file without the empty ones then:

    public static IList<string> ReadFile(string fileName)
    {
        File.ReadAllLines(fileName)
            .SelectMany(line => line.Split(','))
            .Where(item => !string.IsNullOrWhiteSpace(item))
            .ToList();
    }
    
    0 讨论(0)
  • 2021-01-16 01:20

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

    public static IList<string> ReadFile(string fileName)
    {
      var results = new List<string>();
      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.

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