thevan
thevan

Reputation: 10364

How to remove more DataTable Columns using C#.Net?

I have One DataTable may have more Columns. But "NetAmount", "TotalAmount", "Destination" are the DataTable Columns which always present in the DataTable.

Here I want to Remove the three Columns such as "NetAmount", "TotalAmount" and "Destination" from the DataTable and to take the other column values in the DataTable.

I tried like the below and get the Desired Output.

  dtAttribute.Columns.Remove("NetAmount"); //dtAttribute is the Main DataTable
  dtAttribute.Columns.Remove("TotalAmount");
  dtAttribute.Columns.Remove("Destination");
  DataTable dtItem = dtAttribute.Copy();      

But it looks like very childish and lengthy. Is there any other method to do? Please give suggestions.

Upvotes: 1

Views: 8808

Answers (3)

Ali Borjian
Ali Borjian

Reputation: 1108

First select columns which you want to remove, then remove them

List<string> toRemove = dt.Columns.Cast<DataColumn>().Where(c => c.ColumnName.StartsWith("ExtraColumn")).Select(c => c.ColumnName).ToList();
foreach (var col in toRemove) dt.Columns.Remove(col);

Upvotes: 0

Steve Wellens
Steve Wellens

Reputation: 20640

Instead of removing the columns, how about not putting them in the DataTable in the first place?

Upvotes: 0

Heinzi
Heinzi

Reputation: 172468

There's nothing wrong with your code (except that you are copying the table after removing the columns -- are you sure that this is what you want?).

If you want something more abstract (instead of repeating the same line again and again), you might consider removing the columns in a loop:

var dtItem = dtAttribute.Copy();    // if you want to keep a copy of the original table

var toRemove = new string[] {"NetAmount", "TotalAmount", "Destination"};
foreach (col in toRemove)
    dtItem.Columns.Remove(col);

Upvotes: 7

Related Questions