我想检查lastlogindate列是否为null。如果它不为null我想将对象转换为日期时间格式,否则我想使用条件运算符或linq返回为null。
公共类UserBase { public string UserName {get;组; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string PhoneNo { get; set; }
public string MobilePhone { get; set; }
public string GroupName { get; set; }
public DateTime LastLogOnDate { get; set; }
public string Active { get; set; }
public string PlantId { get; set; }
public string UserId { get; set; }
}
以上是我的课程和方法
user = datatable.AsEnumerable().Select(row =>
new EGDataStructure.UserBase
{
UserName = row.Field<string>("User Name"),
FirstName = row.Field<string>("First Name"),
LastName = row.Field<string>("Last Name"),
Email = row.Field<string>("Email ID"),
PhoneNo = row.Field<string>("Phone No"),
MobilePhone = row.Field<string>("Mobile No"),
GroupName = row.Field<string>("Group Name"),
LastLoginDate=row.Field<DateTime>("Last Logged Date")
LastLogOnDate = if ( LastLoginDate != DBNull.Value)??Convert.ToDateTime(row.Field<DateTime>("Last Logged Date"),CultureInfo.InvariantCulture):Null,
Active = row.Field<string>("active"),
UserId = row.Field<string>("userId")
}).ToList();
}
答案 0 :(得分:1)
DateTime
是一种结构,因此您需要Nullable<DateTime>
(或缩写DateTime?
)。
public DateTime? LastLogOnDate { get; set; }
和
LastLogOnDate = row.Field<DateTime?>("Last Logged Date")
如果您想明确区分null
和其他值,例如因为该字段最初是字符串并需要转换:
LastLogOnDate = row.IsNull("Last Logged Date")
? (DateTime?)null
: Convert.ToDateTime(row.Field<string>("Last Logged Date"), CultureInfo.InvariantCulture))