c# Using TextFieldParser to read .csv but unable to replace the created lists empty entries with "0"

55 views Asked by At

New to c#. I am reading two columns from a .csv file and creating a IEnumerable<string[]>. I have the code below that is working, but sometimes a row can be empty (shown by the half height row in the table below) and in that case I would like to replace it with the string "0". Any empty cell is shown as "" in the list when I debug the code.

Lat Lng
51.452703 36.622065
28.721829 41.013330

Raw csv data format:

Col1,Col2,Col3,Col4,Col5,Col6,Lat,Lng,Col9
one street,300,,,GUANGDONG,CN,,,
public static IEnumerable<string[]> ReadCSV(string path)
{
    using (var parser = new TextFieldParser(path))
    {
        parser.Delimiters = new string[] { "," };

        parser.ReadFields(); // read past the header
        while (!parser.EndOfData)
        {
            yield return parser.ReadFields().Skip(6).Take(2).Reverse().ToArray();
        }
    }
}

Below is my attempt to replace the "" with "0", but I am getting the error: string cannot be of zero length, paramenter name oldValue. I understand from that, that it needs something to search for. But I'm not sure where to go now.

public static IEnumerable<string[]> ReadCSV(string path)
{
    string[] test;

    using (var parser = new TextFieldParser(path))
    {
        parser.Delimiters = new string[] { "," };

        parser.ReadFields(); // read past the header
        while (!parser.EndOfData)
        {
            test = parser.ReadFields().Skip(6).Take(2).Reverse().ToArray();
            var replacedNames = test.Select(x => x.Replace("", "0")).ToArray();
            yield return replacedNames;
        }
    }
}
1

There are 1 answers

0
dbc On BEST ANSWER

The fact that x.Replace("", "0") throws is explained in the docs:

Definition

Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.

Exceptions
ArgumentNullException - oldValue is null.
ArgumentException - oldValue is the empty string ("").

Keeping in mind that strings in C# are immutable, if you want to replace empty or whitespace strings with "0", you can do:

x => string.IsNullOrWhiteSpace(x) ? "0" : x