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

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

问题描述

如果数据表中有一个空值,那么最好的方法是什么?

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.

(此数据表由第三方应用程序返回 - 我们正在尝试在应用程序处理数据表之前进行估价)

(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 值进行比较以过滤和管理null价值观以任何你认为合适的方式。

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天全站免登陆