0

我已经阅读了这方面的一些内容,包括如何仅选择 LINQ 中日期最高的记录,但我不知道如何将其应用于稍微复杂的案例。

我正在尝试获取所有内容AdjusterProfileStatusItem,但只选择最新的s.statusDate. 目前,查询只返回所有记录的所有日期;而我只想要所有记录的最新日期。

(from u in db.Users
join a in db.Adjusters
on u.id equals a.userID
join s in db.AdminAdjusterStatus
on a.id equals s.adjusterID
where u.userType.ToLower() == "adjuster"
&& s.status.ToLower() == "approved"

&& s.statusDate.Max() // causes syntax error...

select new AdjusterProfileStatusItem
{
   user = u,
   adjuster = a
})

编辑:

我也试过这个,这给了我一个语法错误......

(from u in db.Users
join a in db.Adjusters
on u.id equals a.userID
join s in db.AdminAdjusterStatus
on a.id equals s.adjusterID
where u.userType.ToLower() == "adjuster"
&& s.status.ToLower() == "approved"
group new { u, a, s } by s.adjusterID into x
select new AdjusterProfileStatusItem
{
    user = u, // u does not exist in context
    adjuster = a, // a does not exist in context
    status = x.Max(y => y.statusDate) // anonymous type does not contain definition for 'statusDate'
})
4

1 回答 1

1

我不确定您对 Lambda 表达式的感受,但我可能会这样做:

db.Users
  .Join(db.Adjusters,
  u => u.Id,
  a => a.UserId,
  (u, a) => new 
  {
       User = u,
       Adjuster = a
  })
  .Join(db.AdminAdjusterStatus,
  a => a.Adjuster.Id,
  s => s.AdjusterId,
  (a, s) => new 
  {
       User = a.User,
       Adjuster = a.Adjuster,
       AdminAdjusterStatus = s
  })
  .Where(x => x.User.userType == "adjuster"
      && x.AdminAdjusterStatus.status == "approved"
      && x.AdminAdjusterStatus.statusDate == db.AdminAdjusterStatus
                             .Where(y => y.AdjusterId == 
                                    x.AdminAdjusterStatus.AdjusterId)
                             .Max(z => z.statusDate))
  .Select(a => new AdjusterProfileStatusItem
  {
      user = a.User
      adjuster = a.Adjuster
  })

**EDIT!!!**


(from u in db.Users
join a in db.Adjusters
on u.id equals a.userID
join s in db.AdminAdjusterStatus
on a.id equals s.adjusterID
where u.userType.ToLower() == "adjuster"
&& s.status.ToLower() == "approved"

&& s.statusDate == GetMaxStatusDate(db.AdminAdjusterStatus.ToList(), s.AdjusterID)

select new AdjusterProfileStatusItem
{
   user = u,
   adjuster = a
})

private DateTime GetMaxStatusDate(List<AdminAdjusterStatus> statuses, int adjusterId)
{
     return (from a in statuses
             where a.AdjusterId == adjusterId
             group a by a.AdjusterId into values
             select values.Max(x => x.statusDate)).FirstOrDefault();
}



 OR 



(from u in db.Users
join a in db.Adjusters
on u.id equals a.userID
join s in db.AdminAdjusterStatus
on a.id equals s.adjusterID
where u.userType.ToLower() == "adjuster"
&& s.status.ToLower() == "approved"

&& s.statusDate == db.AdminAdjusterStatus
                   .Where(x => x.AdjusterId == s.AdjusterId)
                   .Select(y => y.statusDate)
                   .Max();

select new AdjusterProfileStatusItem
{
   user = u,
   adjuster = a
})
于 2013-07-17T16:00:56.750 回答