Remove columns from DataTable in C#

C#asp.net

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

Solution 2 - C#

To remove all columns after the one you want, below code 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);
}

Solution 3 - C#

The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.

So for that, here is what I did, when I came across the same problem.

string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };

foreach (string ColName in ColumnsToBeDeleted)
{
	if (dt.Columns.Contains(ColName))
	    dt.Columns.Remove(ColName);
}

Solution 4 - C#

How about you just select the columns you want like this:

Dim Subjects As String = "Math, English"
Dim SubjectData As DataTable = Table.AsDataView.ToTable(True, Subjects.Split(","))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrian GView Question on Stackoverflow
Solution 1 - C#Tom RitterView Answer on Stackoverflow
Solution 2 - C#Timothy CarterView Answer on Stackoverflow
Solution 3 - C#SU7View Answer on Stackoverflow
Solution 4 - C#Hannington MamboView Answer on Stackoverflow