2012-01-27 57 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"):""});