Linq Max的默认值 [英] Linq Max with Default Value

查看:171
本文介绍了Linq Max的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取用户的上次登录日期,如果不存在登录记录,请返回今天的日期.我需要一些帮助才能到达那里.我收到以下错误,甚至没有默认值组件.

I am trying to get the user's last login date and if no login records exist, return today's date. I am need some help getting there. I am getting the following error and do not even have the default value component.

无法隐式转换类型 "System.Linq.IQueryable"到"System.DateTime?"

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.DateTime?'

DateTime? logdate = from userlog in
                                    (from userlog in db.UserLogEntities
                                     where
                                       userlog.UserID == 1 &&
                                       userlog.Action == "Logon" &&
                                       userlog.ActionTag == "Success"
                                     select new
                                     {
                                         userlog.LogDate,
                                         Dummy = "x"
                                     })
                                group userlog by new { userlog.Dummy } into g
                                select new
                                {
                                    Column1 = (DateTime?)g.Max(p => p.LogDate)
                                };

推荐答案

下面是我想到的.让我知道是否有更好的方法.

Below is what I came up with. Let me know if there is a better way.

LastLogin = (from ul in db.UserLogEntities
                                 where ul.UserID == u.UserID &&
                                    ul.Action == "Logon" &&
                                    ul.ActionTag == "Success"
                                 select ul.LogDate).DefaultIfEmpty(DateTime.Now).Max()

这篇关于Linq Max的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆