如何跳过csv文件中的一些空行并继续读取数据行? c#控制台应用程序

问题描述:

我在我的CVS文件中有5列,前两列有3个空行。我想跳过这些空行。我知道我必须循环通过文件,但我不知道如何做这个过程。

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 however I do not know how to do this process.

任何建议都会感激。

public class Program
{
    static void Main(string[] args)
    {
        var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Santander .csv");
        var fileContents = ReadFile(filePath);
        foreach (var line in fileContents)
        {
            Console.WriteLine(line);
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }

    public static IList<string> ReadFile(string fileName)
    {
        var results = new List<string>();
        var target = File.ReadAllLines(fileName).ToList();
        return results;
    }
}


a 其中子句只保留不 NullOrWhiteSpace (空,空白或只有空格)的行:

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();
}






之后是:对于每行使用拆分获取不同的列,然后检查前2个不为空:


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();
}

更改为语法查询,因为在我看来,我们开始需要 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();
}