سؤال

I want to remove every column after the 3rd column from a CSV file loaded into a datatable, but I'm getting odd results. Here's my code.

System.Data.DataTable csv_datatable = null;
using (System.IO.StreamReader re = new System.IO.StreamReader(model.file.InputStream))
{
    csv_datatable = CsvParser.Parse(re as System.IO.TextReader);
    for (int x = 3; x < csv_datatable.Columns.Count + 1; x++)
    {
        csv_datatable.Columns.RemoveAt(x);
    }
}

My sample CSV file: 7 columns, and I want to keep the first three.

email,first,last,middle,nick,job,phone
roryok@fakedomain.com,rory,wally,ok,danger,developer,555-0123

This is the result I get.

email,first,last,nick,phone
roryok@fakedomain.com,rory,ok,danger,555-0123

As you can see, rather than removing the last columns as I would expect, the code actually removes the 4th and 6th columns.

هل كانت مفيدة؟

المحلول

As usual, figured this out as I was posting, but I'll post the solution anyway in case it helps someone.

As each column is removed, the index for each column changes. So when you remove column 3, 4 becomes the new 3. This code works:

for (int x = 0; x < csv_datatable.Columns.Count; x++)
{
    csv_datatable.Columns.RemoveAt(3);
}     

This will loop over the number of columns, and remove the third column over and over again until everything is gone.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top