0

I'm using this to go through my column headers. Columns that don't equal or contain columnsToKeep are removed. Problem is the DataTable has 100+ columns, so this takes a long time. Is there a faster way of accomplishing this?

var columnsToKeep = new List<string>() { "Summary", "Status", "CF1" };
var toRemove = new List<DataColumn>();

foreach (DataColumn column in dtTable.Columns)
{
    if (!columnsToKeep.Any(name => column.ColumnName == name) && !columnsToKeep.Any(name => column.ColumnName.Contains("CF1")))
    {
        toRemove.Add(column);
    }
}

toRemove.ForEach(col => dtTable.Columns.Remove(col));
lolikols
  • 87
  • 1
  • 5
  • 24
  • 2
    Don't load the unwanted columns in the first place. Data is stored as rows in a DataTable. Removing columns actually modifies all rows – Panagiotis Kanavos Aug 08 '23 at 17:30
  • "so this takes a long time" how long does it take? – Tim Schmelter Aug 08 '23 at 17:36
  • 1
    Maybe create a new Datatable with only the columns you need and copy the desired columns from the original Datatable to the new one? This would prevent you from needing to iterate over all the columns and compare to see if it's a desired column. Something like [this](https://stackoverflow.com/questions/18402324/copy-specific-columns-from-one-datatable-to-another) or [this](https://stackoverflow.com/questions/6183621/copying-data-of-only-few-columns-to-one-more-data-table). But the fastest approach is to only load the desired columns in the original Datatable. – devlin carnate Aug 08 '23 at 17:41
  • Not sure what is the real purpose of this, but the ColumnsCollection has a RemoveAt method where the parameter is the index of the column to remove. Just a normal for...loop in reverse order is enough to find and remove the column from the initial table. – Steve Aug 08 '23 at 17:56

0 Answers0