从 DataTable 中删除所有没有数据的列 [英] Remove all columns with no data from DataTable
本文介绍了从 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?
推荐答案
您可以使用 Compute
方法,像这样:
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");
<小时>
编辑:完整回答问题:
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.
这篇关于从 DataTable 中删除所有没有数据的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文