[英]Check DataTable if a column exists and if it's null
Environment: .Net Framework 3.5 环境:.Net Framework 3.5
I have a DataTable
that can bring back variable amount of columns for the same table in a database and I'm checking if the column exists
and if it does is it null
like the following: 我有一个
DataTable
,它可以为数据库中的同一张表带回可变数量的列,并且我正在检查该列是否exists
,如果exists
,则为null
,如下所示:
This is when I'm mapping a DataTable
to an entity
这是我将
DataTable
映射到entity
Status = dt.Columns["Status"] != null ? row["Status"] == DBNull.Value ? 0 : Convert.ToInt16(row["Status"]) : 0,
Is this pretty standard or might I be missing any other case? 这很标准吗?或者我可能会错过其他情况? Other more concise ways?
其他更简洁的方法?
Everything is better with
Doodles
extension methods: 使用
Doodles
扩展方法,一切都会更好:
public static class DataTableExtensions
{
public static T GetValueOrDefault<T>(this DataRow row, string columnName)
{
return row.GetValueOrDefault<T>(columnName, default(T));
}
public static T GetValueOrDefault<T>(this DataRow row, string columnName, T defaultValue)
{
return row.Table.Columns[ColumnName] != null &&
row[columnName] != DbNull.Value &&
row[columnName] is T ? (T)row[columnName] : defaultValue;
}
}
Usage: 用法:
var Status = row.GetValueOrDefault<Int16>("status");
or 要么
var Status = row.GetValueOrDefault<Int16>("status", -1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.