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;
}
}
}
The fact that
x.Replace("", "0")throws is explained in the docs:Keeping in mind that strings in C# are immutable, if you want to replace empty or whitespace strings with
"0", you can do: