2013-03-06 62 views
0

我有以下查詢返回給我一個賓客列表以及RSVP列表。但是,由於用戶每個事件可以有多個RSVP,我只想獲得最新的。 RSVPs表格有一個提交的日期列。LINQ Query - 通過鍵獲取最新的記錄

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

您是否嘗試過使用'排序依據x.DateProperty descending'? – fiberOptics 2013-03-06 01:42:02

回答

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); 
+0

這隻適用於每位客人。我希望能夠爲多位客人做到這一點 – user1106741 2013-03-06 01:53:59

0

假性 -

group x by username into g 
select new { 
    UserName = g.key // username 
    FirstRsvp = g.OrderByDescending(item => item.RsvpDate).FirstOrDefault() 
} 

希望這是因爲這樣的事情可能不會在SQL中定義的LINQ to對象供應商。如果它是SQL並且它沒有實現,.AsEnumerable()會將查詢拉入內存,然後它將成爲L2O。

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和負載連接的客人對象,給予有一個外鍵關係。

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()