从空列表中读取空 DateTime

我正在尝试使用 Mvc5 从空列表中读取空日期时间


List<TelecomPayments> telPayments = 

    db.TelecomPayments

        .Where(t => t.TelecomAdmin.TelecomAdminID == telecomAdmin.TelecomAdminID)

        .ToList();


telPayments.FirstOrDefault();

DateTime? lastDate = telPayments.FirstOrDefault().ToDate;


if (lastDate == null)

{

    if (telPayments.Count == 0)

    {

    }

}

这是我在控制器中指定的,但仍然通过补偿


料青山看我应如是
浏览 101回答 2
2回答

白衣非少年

使用 LINQ 时,有两组函数:返回IEnumerable<...>(or&nbsp;IQueryable<...>) 的函数和返回 a的函数TResult。如果您编写 LINQ 语句,请始终确保所有中间 LINQ 语句都返回IEnumerable/&nbsp;IQueryable,只有最后一个可能是FirstOrDefault,&nbsp;ToList,&nbsp;Max,Any等。DateTime?&nbsp;lastDate&nbsp;=&nbsp;telPayments &nbsp;&nbsp;&nbsp;&nbsp;.Select(telpayment&nbsp;=>&nbsp;telpayment.ToDate) &nbsp;&nbsp;&nbsp;&nbsp;.FirstOrDefault();

慕标5832272

如果您使用的是 C# 6 或更高版本,则可以使用?。又名“空条件”运算符:List<TelecomPayments> telPayments =&nbsp;&nbsp; &nbsp; db.TelecomPayments&nbsp; &nbsp; &nbsp; &nbsp; .Where(t => t.TelecomAdmin.TelecomAdminID == telecomAdmin.TelecomAdminID)&nbsp; &nbsp; &nbsp; &nbsp; .ToList();DateTime? lastDate = telPayments.FirstOrDefault()?.ToDate;这只会.ToDate在它之前的部分不为空时尝试访问。如果您使用的是较旧的 C# 版本,则必须进行更明确的 null 检查:List<TelecomPayments> telPayments =&nbsp;&nbsp; &nbsp; db.TelecomPayments&nbsp; &nbsp; &nbsp; &nbsp; .Where(t => t.TelecomAdmin.TelecomAdminID == telecomAdmin.TelecomAdminID)&nbsp; &nbsp; &nbsp; &nbsp; .ToList();DateTime? lastDate = null;var payment = telPayments.FirstOrDefault();if (payment != null) lastDate = payment.ToDate;
打开App,查看更多内容
随时随地看视频慕课网APP