我正在将Excel文件转换为DataTable,我想检查列中是否有空值。有没有办法在不指定列名的情况下执行此操作?类似的东西:
var nullValues = excelTable.AsEnumerable().Where(row => row.IsNull(0));
但是没有指定列索引?
答案 0 :(得分:3)
你可以使用datarow的ItemArray和linq来检查任何空值:
var nullValues = excelTable.AsEnumerable().Where(row => row.ItemArray.Any(v=>v is DBNull));
答案 1 :(得分:1)
您可以遍历DataTable中存在的字段并查找空值。请记住,您需要检查DBNull的值。在.NET引入Nullable类型之前设计的这种类型。
“DBNull表示从数据库返回的不存在的值。例如,在数据库中,表格行中的列可能不包含任何数据。该列被认为根本不存在而不是仅仅没有值。” Reference.
var dt = new DataTable();
var cols = new[]
{
new DataColumn("OrderDetailId", typeof(int)),
new DataColumn("OrderId", typeof(string)),
new DataColumn("Product", typeof(string)),
new DataColumn("UnitPrice", typeof(decimal)),
new DataColumn("OrderQty", typeof(int))
};
dt.Columns.AddRange(cols);
object[] rows =
{
new object[] {1, "O0001", "Mountain Bike", 1419.5, 36},
new object[] {2, "O0001", "Road Bike", 1233.6, 16},
new object[] {3, "O0001", "Touring Bike", 1653.3, 32},
new object[] {4, "O0002", null, 1419.5, 24},
new object[] {5, "O0002", "Road Bike", 1233.6, 12},
new object[] {6, "O0003", "Mountain Bike", null, 48},
new object[] {7, "O0003", "Touring Bike", 1653.3, 8},
};
foreach (object[] row in rows)
dt.Rows.Add(row);
var dtRows = dt.AsEnumerable().Select(x => x.ItemArray).ToList();
var rowsWithNullValue = dtRows.Where(x => x.Any(y => y == null || y == DBNull.Value)).ToList();
if (dtRows.Any(x => x.Any(y => y == null || y == DBNull.Value)))
{
var nullRecordCount = rowsWithNullValue.SelectMany(x => x).Count(x => x == null || x == DBNull.Value);
Console.WriteLine($"The table contains ({nullRecordCount}) null values.");
}