子查询在C#中的LINQ查询中获取最大值

时间:2011-10-21 01:27:44

标签: c# linq linq-to-sql c#-3.0

我正在尝试创建一个子查询以从表中获取最新日期,与查询的其余部分无关。

我的查询如下。我想在子表中选择最高日期作为值,并将其投影到我的模型中。

我的其他 tabe是反馈,并包含日期值和用户名字段

return (from t1 in db.TaskAppointmentOpens

                from t2 in db.Tasks.Where(t => (t.Task_ID == t1.Parent_Task_ID))

                from t3 in db.UserNames.Where(t => (t.User_Username == t2.OwnerTypeItem_ID))

                where ((t2.Item_ID > 0) && (t2.Type_ID > 0) && (t2.Creator == user) && (t1.AppointmentEnd < DateTime.Now) && (t1.AppointmentStart > EntityFunctions.AddMonths(DateTime.Now, -6)) && (from i in db.AppointmentFeedbacks where i.AppointmentId == t1.ID select i).Count() == 0)

                group new {t2, t3} by new { 
                  t2.OwnerTypeItem_ID, t3.Name
                } into g

                let oldestAppointment = g.Min(uh => uh.t2.Due_Date)

                    select new TelesalesNeglectedFeedbackModel
                    {
                        UserFullName = g.Key.Name,
                        QtyOutstanding = g.Select(x => x.t2.Task_ID).Distinct().Count(),
                        OldestAppointment = oldestAppointment
                        LastDateInOtherTable = HERE <======
                    }).Take(5).ToList();

1 个答案:

答案 0 :(得分:1)

您应该能够以这种方式访问​​表格和字段:

LastDateInOtherTable = db.Feedback.Max(f => f.Date)

或者像对其他列一样使用let子句,然后稍后再分配:

let lastDate = db.Feedback.Max(f => f.Date)
...
LastDateInOtherTable = lastDate