2012-01-27 41 views
0

我有以下的地方我只需要從ReqDate和RepDeclined得到的日期(不是日期時間)都是可以爲空的日期時間字段。LINQ DateTime可以爲空的日期字段的格式

var info = from pr in db.Prog   
join tf in db.In_Lens   
on pr.PID equals tf.PID   
select new   
{ ReqDate = String.Format("{0:MM/dd/yyyy}",tf.ReqDate),   
    ReqDeclinedDate = tf.ReqDeclined.ToString("MM/dd/yyyy")  
}).ToList() 

它不工作,因爲ReqDate和RepDeclined都是可空的日期時間字段。我也試過String.Format,但沒有運氣。

回答

0

var info = from pr in db.Prog   
join tf in db.In_Lens   
on pr.PID equals tf.PID   
select new   
{ 
    ReqDate = (tf.ReqDate == null ? "" : tf.ReqDate.ToString("MM/dd/yyyy")), 
    ReqDeclinedDate = (tf.ReqDeclined == null ? "" : tf.ReqDeclined.ToString("MM/dd/yyyy")) 
}).ToList() 

,以避免因.ToString調用空對象的NullReferenceException異常。在這兩種情況下

使用String.Format

var info = from pr in db.Prog   
join tf in db.In_Lens   
on pr.PID equals tf.PID   
select new   
{ 
    ReqDate = String.Format("{0:MM/dd/yyyy}",tf.ReqDate), 
    ReqDeclinedDate = String.Format("{0:MM/dd/yyyy}",tf.ReqDeclined) 
}).ToList() 
0

曾與此掙扎了一會兒。發現這對我有用。

var info = (from pr in db.Prog   
      join tf in db.In_Lens   
      on pr.PID equals tf.PID   
      select new { tf.ReqDate, tf.ReqDeclined}).ToList(); 

var infoFormatted = info.Select(x => new { ReqDate = x.ReqDate.HasValue?x.ReqDate.Value.ToString("MM/dd/yyyy"):"", ReqDeclined = x.ReqDeclined.HasValue?x.ReqDeclined.Value.ToString("MM/dd/yyyy"):""});