.NET importing, remove ending columns that have empty header column

281 views Asked by At

I have a CSV file that has over 16,000 columns to import. However, the file really only has up to 12 columns, with two empty headers in between. In the screenshot what is the best way to remove the 12 index and up to the 16,000 from the header array quickly in .NET? 8,9 should stay since 10,11 have header values. Right now I am going through every column on each row, meaning 16,000 checks per row when it should be 12 (0-11 index).

 protected Dictionary<int, string> Headers = new Dictionary<int, string>();

enter image description here

1

There are 1 answers

2
Philippe Paré On BEST ANSWER

I would loop backwards to figure out the last index in the header array where there's something.

int lastColumn = 0;

for (lastColumn = columns.Length - 1; lastColumn >= 0 ; lastColumn--)
{
    if (!string.IsNullOrWhiteSpace(columns[i]))
    {
        break;
    }
}

// stop at lastColumn, skipping all the empty columns at the end
for (int i = 0; i <= lastColumn; i++)
{
    // Do something
}