Удалить столбцы из таблицы данных, которых нет в списке <string> - PullRequest
0 голосов
/ 23 сентября 2019

У нас есть это List<string>

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

И еще Datatable [B] со следующими столбцами

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

Как нам удалить все столбцы которые не найдены в List<string> A из Datatable B?

Ответы [ 4 ]

1 голос
/ 23 сентября 2019

Я предлагаю простой цикл for:

  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);
1 голос
/ 23 сентября 2019

Вы можете попробовать код ниже.

 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(" ");
            }
1 голос
/ 23 сентября 2019

Если вы просто хотите удалить все столбцы, не найденные в списке '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);
1 голос
/ 23 сентября 2019

Вы можете сделать что-то вроде этого

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].Name.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
      }
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...