如何檢查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