我有一组数据,想要删除包含null或空值的列。示例应如下所示:
REGION | STATE | COUNTY | PROGRAM 1 | PROGRAM 2 | PROGRAM 3 | PROGRAM 4 | ...
------------------------------------------------------------------------------
"North" | null | null | "Foo" | null | "Bar" | null |...
"East" | null | null | "Duh" | null | "Whew" | null |...
结果可能是:
REGION | PROGRAM 1 | PROGRAM 3 | ...
-------------------------------------
"North" | "Foo" | "Bar" | ...
"East" | "Duh" | "Whew" | ...
请注意,空列非常一致(即STATE一直为null)。作为LINQ的新手,我无法找到实现预期结果的正确方法。任何建议/代码样本将不胜感激。
答案 0 :(得分:4)
// get all columns to array
var columns = yourDataTable.Columns.Cast<DataColumn>().ToArray();
foreach(var col in columns) {
// check column values for null
if (yourDataTable.AsEnumerable().All(dr => dr.IsNull(col)))
{
// remove all null value columns
yourDataTable.Columns.Remove(col);
}
}
答案 1 :(得分:1)
如果列是一致的,那么您问的问题是“如何仅选择特定列?”
var result = from x in myTable
select new { x.Region, x.Program1, x.Program3 };
或使用扩展方法格式:
var result = myTable.Select(x => new { x.Region, x.Program1, x.Program3 });