如何检查Linq中的空值?LINQ检查空值
我有一个第三方代码,返回一个DataTable
,列类型DateTime
可为空。
我的代码:
var profile = (from d in ds.Tables[0].AsEnumerable()
select new User
{
FirstName = d["FirstName"].ToString(),
Birthdate = Convert.ToDateTime(d["BirthDate"].ToString())
}).FirstOrDefault();
返回一个错误的Object cannot be cast from DBNull to other types
上Birthdate=
声明。
我用下面的代码尝试,但返回一个转换异常(无法从字符串转换为日期时间?)
Birthdate = (DateTime?)d["BirthDate"].ToString();
有没有办法来速记检查空值?
+1中使用它,因为这是DataSetExtenions的构建内容; Linq访问数据集。 – dwerner 2012-07-09 02:09:02
这个工作很棒。但是当我有一个对象作为属性时,例如'User.Location'和'Location'对象具有'ID'属性,代码'User.Location.Id = d.Field(“LocationId”)'失败。我在这里做错了什么? –
Devmonster
2012-07-09 03:13:31