从 C# 中的 DataTable 中删除列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/75123/
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
Remove columns from DataTable in C#
提问by Brian G
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.
我有一个数据集,我从中得到一个数据表,我从函数调用中返回。它有 15-20 列,但是我只想要 10 列数据。
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.
有没有办法删除我不想要的那些列,将 DataTable 复制到另一个只定义了我想要的列,或者迭代集合并只使用我需要的列更好。
I need to write the values out to a fixed length data file.
我需要将值写入固定长度的数据文件。
采纳答案by Tom Ritter
Aside from limiting the columns selected to reduce bandwidth and memory:
除了限制选择的列以减少带宽和内存之外:
DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
回答by Timothy Carter
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.
要删除您想要的列之后的所有列,下面的代码应该可以工作。它将在索引 10 处删除(记住列是基于 0 的),直到列计数为 10 或更少。
DataTable dt;
int desiredSize = 10;
while (dt.Columns.Count > desiredSize)
{
dt.Columns.RemoveAt(desiredSize);
}
回答by Safi Ullah
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
.
该问题已被标记为已回答,但我想该问题表明该人想要从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);
}