3

我有一个包含 20 列的数据表。但我不需要当前处理的所有列,除了 5。所以我做了以下操作来删除列

List<string> clmnames = new List<string>() { "clm6","clm7"..."clm20" };
foreach (string dcName in clmnames)
{
  TestAndRemoveColumn(dcName, ds.Tables["TestTable"]);
}


 private void TestAndRemoveColumn(string dcName,DataTable datatable)
 {
       DataColumnCollection dcCollection = datatable.Columns;
       if (dcCollection.Contains(dcName))
       {
           dcCollection.Remove(dcName);
       }
 }

除了循环 15 次之外,还有其他方法可以轻松实现使用吗?

4

5 回答 5

4

尝试这个

List<string> listtoRemove = new List<string> { "CLM6", "CLM7", "CLM20" };
for (int i = dt.Columns.Count - 1; i >= 0; i--)
{
   DataColumn dc = dt.Columns[i];
   if (listtoRemove.Contains(dc.ColumnName.ToUpper()))
   {
       dt.Columns.Remove(dc);
   }
}
于 2016-02-11T18:35:34.123 回答
3

在某些情况下,克隆 DataTable 并指定要复制的列可能更可取。

DataView view = new DataView(table);
DataTable table2 = view.ToTable(false, "clm6", "clm7", ...);
于 2015-02-07T17:02:13.590 回答
1

问题似乎出在您的代码中,您从数据表中获取所有列,然后删除列,但您没有再次将列分配给该数据表,首先您获得列

   DataColumnCollection dcCollection = datatable.Columns; // get cols
   if (dcCollection.Contains(dcName))
   {
       dcCollection.Remove(dcName); /// remove columns
     // but you have not updated you datatable columns.
        here should be something like this
       datatable.Columns = dcCollection; /// i don't know this will work or not check it
   }

尝试这个

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

您可以将它们用作

private void TestAndRemoveColumn(string dcName,DataTable datatable)
{
    DataTable dt = datatable; 
    dt.Columns.Remove("dcName");      
}
于 2012-07-26T10:09:46.997 回答
1

或者,您可以像这样只选择所需的列(在您的情况下只有 5 个)。

        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Value");

        dt.Rows.Add("1", "One");
        dt.Rows.Add("2", "Two");

        string[] arr= new string[1];
        arr[0] = "Value";//add the required columns to the array
        
        //return only the required columns.
        DataTable dt2 = dt.DefaultView.ToTable(false, arr);
于 2012-07-26T10:45:56.570 回答
0

您可以将要删除的列与可用列连接起来:

var keepColNames = new List<String>(){ "clm5" };
var allColumns   = tbl.Columns.Cast<DataColumn>();
var allColNames  = allColumns.Select(c => c.ColumnName);
var removeColNames = allColNames.Except(keepColNames);
var colsToRemove = from r in removeColNames
                   join c in allColumns on r equals c.ColumnName
                   select c;
while (colsToRemove.Any())
    tbl.Columns.Remove(colsToRemove.First());

如果您知道您只有很少的剩余列,则可以添加列:

var colsToAdd = (from keepCol in keepColNames
                 join col in tbl.Columns.Cast<DataColumn>()
                 on keepCol equals col.ColumnName
                 select col).ToList();
tbl.Columns.Clear();
foreach (var colToAdd in colsToAdd)
    tbl.Columns.Add(colToAdd);
于 2012-07-26T10:10:44.220 回答