我如何可以验证是否列在DataRow对象存在吗? [英] How can I validate if the column exist in a DataRow object?

查看:130
本文介绍了我如何可以验证是否列在DataRow对象存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private int EmploymentID { get; set; }

private void MapFields(DataRow row)
{
        if(row.HasError)
          EmploymentID = Convert.ToInt32(row["EmploymentID"].ToString());
}



中的代码表明,它验证,如果DataRow对象有错误就其行,但我想,如果它曾经存在验证。有相当使用的DataRow的HasError方法的代码的方法?

The code shows that it validates if the DataRow object has error on its row but I want to validate if it ever exist. Is there an approach for the code rather using HasError method of DataRow?

感谢您的任何答案。

推荐答案

DataRow中有一个表属性,引用的,它是从哪里来的DataTable
DataTable中有一个列属性,它是一个 DataColumnCollection

DataRow has a Table property, referencing the DataTable that it came from. DataTable has a Columns property, which is a DataColumnCollection.

枚举该列表将让你确定表是否包含所需列。需要注意的是表上的所有行具有相同的列。

Enumerating this list will let you determine if the table contains the column you want. Note that ALL rows on the table have identical columns.

例如:

bool containsColumn = row.Table.Columns.Any(column => column.ColumnName == "EmploymentID");



值得指出的是,你可能会需要检查平等的DBNull ,除非你是100%肯定的EmploymentID永远不能返回null。

It's worth pointing out that you will likely need to check for equality to DBNull, unless you are 100% certain the EmploymentID can never be returned null.

此外,如果EmploymentID列的类型为整数,那么就可以避免任何需要进行类型转换,使用直接转换:

Also, if the EmploymentID column is typed as an integer, then you can avoid any need for type conversion, by using a direct cast:

EmploymentID = (int)row["EmploymentID"]; 



或可替换地,可使用的 DataRowExtensions 获取了一个非常巧妙的方法,其中完成所有的空检查您:

or alternatively, use DataRowExtensions for a much neater approach, which does all the null checking for you:

EmploymentID =  row.Field<int?>("EmploymentID"); 

如果EmploymentID不是一个可空INT,那么你就可以像合并值:

If EmploymentID isn't a nullable int, then you can coalesce the value like:

EmploymentID =  row.Field<int?>("EmploymentID") ?? 0;

这篇关于我如何可以验证是否列在DataRow对象存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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