user4602228
user4602228

Reputation:

Remove columns from DataTable which are not in List<string>

We have this List<string>

List<string> A = ['a','b','c']

And another Datatable [B] with the following columns

'a' 'b' 'c' 'd' 'e' // the columns of DataTable B

How do we remove all of the columns which are not found in List<string> A from Datatable B?

Upvotes: 0

Views: 3316

Answers (4)

Cyrille Con Morales
Cyrille Con Morales

Reputation: 957

You can do something like this

int numCols = dt.Columns.Count;

foreach(String str in A){//loop all strings in arrays

 for(int i=0;i<numCols;i++){//loop all columnames in dataTable B
      string columnName =dt.Columns[i].ColumnName.ToString();//get column Name
      //check if columnNames in B are equal to 
      if(!str.Equals(columnName){
        //remove column
         dt.Columns.RemoveAt(i);
      }else{
       //column name is equal to the string array
      }
   }
}

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

I suggest a simple for loop:

  DataTable table = new DataTable();

  table.Columns.Add("a", typeof(string));
  table.Columns.Add("b", typeof(string));
  table.Columns.Add("C", typeof(string));
  table.Columns.Add("d", typeof(string));
  table.Columns.Add("e", typeof(string));
  table.Columns.Add("F", typeof(string));

  var A = new List<string> { "a", "b", "c" };

  // HashSet is a better collection in the context:
  //  1. We can specify comparer (e.g. we can ignore case)
  //  2. It's faster if the collection has many items
  // Sure, you can put A.Contains instead of columnsToKeep.Contains
  HashSet<string> columnsToKeep = 
    new HashSet<string>(A, StringComparer.OrdinalIgnoreCase);

  // For i-th column we should either either keep column (do nothing) or remove it
  for (int i = table.Columns.Count - 1; i >= 0; --i)
    if (!columnsToKeep.Contains(table.Columns[i].ColumnName))
      table.Columns.RemoveAt(i);

Upvotes: 1

ArcX
ArcX

Reputation: 817

If you just want to remove all the columns not found in list 'A'

var A = new List<string> { "a", "b", "c" };
var toRemove = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).Except(A).ToList();

foreach (var col in toRemove) dt.Columns.Remove(col);

Upvotes: 1

SUNIL DHAPPADHULE
SUNIL DHAPPADHULE

Reputation: 2863

You can try below code.

 List<string> A = new List<string>() { "a", "b", "c" };

            DataTable dt = new DataTable();
            dt.Columns.Add("a");
            dt.Columns.Add("b");
            dt.Columns.Add("c");
            dt.Columns.Add("d");
            dt.Columns.Add("e");
            foreach (string col in A)
            {
                dt.Columns.Remove(col);
            }
            foreach (DataColumn column in dt.Columns)
            {
                WriteLine(column.ColumnName);
                WriteLine(" ");
            }

Upvotes: 0

Related Questions