我有以下查询,它返回一个客人列表以及一系列RSVP。但是,由于用户每个事件可以有多个RSVP,我只想获得最新的。 RSVP表具有提交的日期列。
from guest in Guests
join rsvp in RSVPs.Where(o => o.EventID == "1234")
on guest.UserName equals rsvp.UserName into sr
from x in sr.DefaultIfEmpty()
select new
{
guest,
x
}
答案 0 :(得分:0)
按日期排序并取1:
(from guest in Guests
join rsvp in RSVPs.Where(o => o.EventID == "1234")
on guest.UserName equals rsvp.UserName into sr
from x in sr.DefaultIfEmpty()
orderby x.RSVPDate desc
select new
{
guest,
x
})
.Take(1);
答案 1 :(得分:0)
假 -
group x by username into g
select new {
UserName = g.key // username
FirstRsvp = g.OrderByDescending(item => item.RsvpDate).FirstOrDefault()
}
希望这是对象的LINQ,因为这种事情可能无法在SQL提供程序中定义。如果是SQL并且没有实现,.AsEnumerable()会将查询拉入内存,然后从那里开始是L2O。
答案 2 :(得分:0)
from guest in Guests
join rsvp in RSVPs.Where(o => o.EventID == "1234")
on guest.UserName equals rsvp.UserName into sr
from x in sr.DefaultIfEmpty()
select new
{
guest,
guest.RSVPs.Where(o => o.EventID =="1234")
.OrderByDesc(o=>o.SubmittedDate)
.FirstOrDefault()
}
实际上,你也可以尝试这个,想法是你加载正确的RSVP并加载附加的guest对象,因为有一个外键关系。
context.RSVPs.Include("Guest").Where(o => o.EventID =="1234").OrderByDesc(o=>o.SubmittedDate).FirstOrDefault()
否则这可能是一个选择:
(from rsvp in context.RSVP
where rsvp.EventId == "1234"
join guest in context.Guests on rsvp.UserName equals guest.UserName
select new {rsvp, guest}
orderby desc rsvp.SubmittedDate).FirstOrDefault()