C# 从数据表中删除列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11667015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:43:26  来源:igfitidea点击:

Remove columns from datatable

c#linq

提问by Pradeep

I have a datatable with 20 columns. But i don't need all the columns for the current processing except 5. So i did the below to remove the columns

我有一个包含 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);
       }
 }

Instead of looping through the 15 times is there any other way to achieve using easily ?

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

回答by Waqar Janjua

Problem seems to be in your code, you get all the comlumns from the datatable then remove the columns but you have not again assign the columns to that datatable first you get columns

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

   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
   }

Try this

尝试这个

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

you can use them as

你可以将它们用作

private void TestAndRemoveColumn(string dcName,DataTable datatable)
{
    DataTable dt = datatable; 
    dt.Columns.Remove("dcName");      
}

回答by Tim Schmelter

You could join the columns you want remove with the available columns:

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

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());

If you know that you only have few remaining columns, you could add the column(s):

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

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);

回答by Manjunath K Mayya

Alternatively you can select only the required columns(Only 5 in your case) like this.

或者,您可以像这样只选择所需的列(在您的情况下只有 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);

Hope this helps.

希望这可以帮助。

回答by SergeyA

In some scenarios may be preferable to clone DataTable and specify columns to copy.

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

DataView view = new DataView(table);
DataTable table2 = view.ToTable(false, "clm6", "clm7", ...);

回答by K.Zelect

try this

尝试这个

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);
   }
}