你可以使用这个方法:
public static void RemoveNullColumns(ref DataTable tbl, params string[] ignoreCols)
{
var columns = tbl.Columns.Cast<DataColumn>()
.Where(c => !ignoreCols.Contains(c.ColumnName, StringComparer.OrdinalIgnoreCase));
var rows = tbl.AsEnumerable();
var nullColumns = columns.Where(col => rows.All(r => r.IsNull(col))).ToList();
foreach (DataColumn colToRemove in nullColumns)
tbl.Columns.Remove(colToRemove);
}
您的样品:
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("A", typeof(int));
table.Columns.Add("B", typeof(int));
table.Columns.Add("C", typeof(int));
table.Rows.Add(1, 1, 2, null);
table.Rows.Add(2, 2, 4, null);
RemoveNullColumns(ref table, "ID");
DataView result = table.DefaultView;
结果(删除了“C”列):
ID A B
1 1 2
2 2 4
这是一个不修改原始表但创建副本的重载:
public static DataTable RemoveNullColumns(DataTable tbl, params string[] ignoreCols)
{
DataTable copy = tbl.Copy();
var columns = copy.Columns.Cast<DataColumn>()
.Where(c => !ignoreCols.Contains(c.ColumnName, StringComparer.OrdinalIgnoreCase));
var rows = copy.AsEnumerable();
var nullColumns = columns.Where(col => rows.All(r => r.IsNull(col))).ToList();
foreach (DataColumn colToRemove in nullColumns)
copy.Columns.Remove(colToRemove);
return copy;
}