从DataTable中删除所有没有数据的列 [英] Remove all columns with no data from DataTable

查看:263
本文介绍了从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?

推荐答案

您可以使用 计算 方法,如下所示:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆