Remove columns from DataTable in C#


Question

I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data.

Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need.

I need to write the values out to a fixed length data file.

1
99
9/16/2008 6:00:05 PM

Accepted Answer

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
270
7/17/2018 10:50:45 AM

To remove all columns after the one you want, this little function should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.

        DataTable dt;
        int desiredSize = 10;

        while (dt.Columns.Count > desiredSize)
        {
            dt.Columns.RemoveAt(desiredSize);
        }

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon