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

后端 未结 2 1266
生来不讨喜
生来不讨喜 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 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 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 ReadFile(string fileName)
    {
        File.ReadAllLines(fileName)
            .SelectMany(line => line.Split(','))
            .Where(item => !string.IsNullOrWhiteSpace(item))
            .ToList();
    }
    

提交回复
热议问题