检查数据表中是否包含空值的最佳方法 [英] Best way to check if a Data Table has a null value in it

查看:26
本文介绍了检查数据表中是否包含空值的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查数据表中是否有空值的最佳方法是什么?

what is the best way to check if a Data Table has a null value in it ?

在我们的场景中,大多数情况下,一列的值都是空值.

Most of the time in our scenario, one column will have all null values.

(此数据表由第 3 方应用程序返回 - 我们试图在我们的应用程序处理数据表之前进行验证)

(This datatable is returned by a 3rd party application - we are trying to put a valiadation before our application processes the data-table)

推荐答案

尝试将列的值与 DBNull.Value 值进行比较,以您认为合适的任何方式过滤和管理空值.

Try comparing the value of the column to the DBNull.Value value to filter and manage null values in whatever way you see fit.

foreach(DataRow row in table.Rows)
{
    object value = row["ColumnName"];
    if (value == DBNull.Value)
        // do something
    else
        // do something else
}

有关 DBNull 类的更多信息

如果要检查表中是否存在空值,可以使用此方法:

If you want to check if a null value exists in the table you can use this method:

public static bool HasNull(this DataTable table)
{
    foreach (DataColumn column in table.Columns)
    {
        if (table.Rows.OfType<DataRow>().Any(r => r.IsNull(column)))
            return true;
    }

    return false;
}

这会让你写这个:

table.HasNull();

这篇关于检查数据表中是否包含空值的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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