Home > Blockchain >  Reading from a csv file, and removing any rows that only have ""
Reading from a csv file, and removing any rows that only have ""

Time:11-05

Reading from a csv file using stream reader and then splitting each value from the row that's being read by a comma.

I would like to remove any row that has empty values within the whole row.

{"test", "test", "test", "test"}
{"test1", "test1", "test1", "test1"}
{"", "", "", ""}

I would like my method to not process that third row if its empty.

using (StreamReader reader = new StreamReader(stream))
            {
                reader.ReadLine();

                while (reader.Peek() != -1)
                {

                    var line = reader.ReadLine();

                    string[] data = line.Split(',');

                    // Convert data into an object
                    ...
                }
            }

I would only like to convert the data into an object if it doesn't look like the 3rd array. {"", "", "", ""}

CodePudding user response:

You can use Linq

// At least 1 empty value
bool hasEmpty = data.Any(string.IsNullOrWhiteSpace);

// All values are empty
bool allEmpty = data.All(string.IsNullOrWhiteSpace);

CodePudding user response:

Just add a simple if statement:

if (data.Any() && !data.All(a => a == string.Empty))
{
   // Convert data into an object
}
  • Related