C# 从 DataTable 中删除所有没有数据的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1766902/
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 all columns with no data from DataTable
提问by Larsenal
If all the items for a particular column are empty, I want to remove that column from the DataTable. What's the most elegant way to do this operation on all columns in the DataTable?
如果特定列的所有项目都为空,我想从 DataTable 中删除该列。对 DataTable 中的所有列执行此操作的最优雅方法是什么?
采纳答案by SLaks
You can use the Compute
method, like this:
您可以使用该Compute
方法,如下所示:
if (table.Compute("COUNT(ColumnName)", "ColumnName <> NULL") == 0)
table.Columns.Remove("ColumnName");
Alternatively, you can use LINQ:
或者,您可以使用 LINQ:
if (table.AsEnumerable().All(dr => dr.IsNull("ColumnName")))
table.Columns.Remove("ColumnName");
EDIT: To completely answer the question:
编辑:要完全回答这个问题:
foreach(var column in table.Columns.Cast<DataColumn>().ToArray()) {
if (table.AsEnumerable().All(dr => dr.IsNull(column)))
table.Columns.Remove(column);
}
You need to call ToArray
because the loop will modify the collection.
您需要调用,ToArray
因为循环会修改集合。
回答by Anon
Function RemoveEmptyColumns(Datatable As DataTable) As Boolean
Dim mynetable As DataTable = Datatable.Copy
Dim counter As Integer = mynetable.Rows.Count
Dim col As DataColumn
For Each col In mynetable.Columns
Dim dr() As DataRow = mynetable.Select(col.ColumnName + " is Null ")
If dr.Length = counter Then
Datatable.Columns.Remove(col.ColumnName)
Datatable.AcceptChanges()
End If
return true
end function
回答by RameezAli
public static void RemoveNullColumnFromDataTable(DataTable dt)
{
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
if (dt.Rows[i][1] == DBNull.Value)
dt.Rows[i].Delete();
}
dt.AcceptChanges();
}
回答by Imran Ahmed
private static void RemoveUnusedColumnsAndRows(DataTable table)
{
for (int h = 0; h < table.Rows.Count; h++)
{
if (table.Rows[h].IsNull(0) == true)
{
table.Rows[h].Delete();
}
enter code here
}
table.AcceptChanges();
foreach (var column in table.Columns.Cast<DataColumn>().ToArray())
{
if (table.AsEnumerable().All(dr => dr.IsNull(column)))
table.Columns.Remove(column);
}
table.AcceptChanges();
}
回答by Manish sharma
You clear all column in datatable.you use like that.
您清除数据表中的所有列。您可以这样使用。
datatable.Columns.Clear();
数据表.Columns.Clear();