【问题标题】:C# - DataTable Select columns with null value LINQ [closed]C# - DataTable 选择具有空值 LINQ 的列
【发布时间】:2018-01-19 22:57:28
【问题描述】:

我正在将 Excel 文件转换为 DataTable,并且我想检查列中是否有任何空值。有没有办法在不指定列名的情况下做到这一点?比如:

var nullValues = excelTable.AsEnumerable().Where(row => row.IsNull(0));

但是没有指定列索引?

【问题讨论】:

  • excelTable的类型是DataTable吗?
  • 是的,它是一个数据表
  • @AndreVillanueva 欢迎来到Stack Overflow!你问了两个不同的问题,这使得很难独立地回答它们,并且很难独立地对每个问题的答案进行投票。我已经编辑了你的第二个问题。您应该为此提出一个单独的问题。您的第二个答案的文本可用here。
  • 只有问题,没有答案...

标签: c# linq datatable rows


【解决方案1】:

您可以将数据行的 ItemArray 与 linq 一起使用来检查任何空值:

var nullValues = excelTable.AsEnumerable().Where(row => row.ItemArray.Any(v=>v is DBNull));

【讨论】:

  • 我删除了第二个问题 (see comment),并编辑了您的答案以匹配。请记住,如果您不同意,您的原件将在编辑历史记录中。谢谢!
【解决方案2】:

您可以遍历 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.");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多