从数据表中没有数据删除所有列 [英] Remove all columns with no data from DataTable
本文介绍了从数据表中没有数据删除所有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果所有的特定列中的项目是空的,我想从数据表删除列。什么是最优雅的方式做DataTable中的所有列此操作?
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?
推荐答案
您可以使用的 计算
方法,就像这样:
You can use the Compute
method, like this:
if (table.Compute("COUNT(ColumnName)", "ColumnName <> NULL") == 0)
table.Columns.Remove("ColumnName");
另外,你可以使用LINQ:
Alternatively, you can use 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);
}
您需要调用的ToArray
因为循环将修改集合。
You need to call ToArray
because the loop will modify the collection.
这篇关于从数据表中没有数据删除所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文