2009-09-10 18 views
0

我的現實生活中的例子太晦澀解釋兩個表,但是這是我想要做的一個很好的近似......需要幫助的LINQ查詢加入含有周期性事件

Month表有列:IdName

Holiday表中的列:IdMonthIdDayOfMonthName

Appointment表中的列:IdMonthIdDayOfMonth,Description

如何生成按月份和月份排列的唯一事件(節假日和約會)列表?

樣品結果:

Month Holiday  Day Appointment Day 
---------------------------------------- 
Nov      Fly to NYC 25 
Nov T-Giving 26 
Nov      Fly home  29 
Dec Xmas  25 

所以,我想爲節日和事件單獨的列,但我希望他們全部是唯一的,在月日的順序列出。

這裏是我到目前爲止(見在線評論):

var events = 
    from 
     m in GetMonths() 
    join 
     h in GetHolidays() 
     on m.Id equals h.MonthId 
    join 
     a in GetAppointments() 
     on m.Id equals a.MonthId 
    where 
     //something that narrows all combinations of events to only unique events 
    orderby 
     m.Id, 
     // something that interleaves h.DayOfMonth with m.DayOfMonth 
    select 
     new 
     { 
      Month = m.Name, 
      Holiday = h.Name, 
      HolidayDay = h.DayOfMonth, 
      Appointment = a.Description, 
      AppointmentDay = a.DayOfMonth 
     }; 
+0

您可以定義「獨特」的含義嗎?你在預約表中有多次相同的事件?你每天只想要一個約會/假期嗎? – ristonj

+0

獨一無二,我的意思是每行有一個事件(假期*或*預約),並且沒有事件重複。 – devuxer

回答

1

下面是使用UNION替代LEFT OUTER的備選答案,它返回您正在查找的結果集(我認爲我的第一個答案完全可以滿足您的「獨特」要求):

var a = from m in month 
     join h in holiday on m.Id equals h.MonthId 
     select new 
     { 
      MonthId = m.Id, 
      Month = m.Name, 
      Holiday = h.Name, 
      HolidayDay = h.DayOfMonth, 
      Appointment = "", 
      AppointmentDay = 0 

     }; 

var b = from m in month 
     join p in appointments on m.Id equals p.MonthId 
     select new 
     { 
      MonthId = m.Id, 
      Month = m.Name, 
      Holiday = "", 
      HolidayDay = 0, 
      Appointment = p.Description, 
      AppointmentDay = p.DayOfMonth 
     }; 

var events = from o in a.Union(b) 
      orderby o.MonthId, o.HolidayDay + o.AppointmentDay 
      select o; 
+0

正是我在找的東西。謝謝! – devuxer

0

你需要做的LEFT OUTER在SQL加入了LINQ看起來像這樣(未經):

var events = 
    from 
     m in GetMonths() 
    groupjoin 
     h in GetHolidays() 
     on m.Id equals h.MonthId 
     into hol = group 
    from 
     h in hol.DefaultIfEmpty() 
    groupjoin 
     a in GetAppointments() 
     on m.Id equals a.MonthId 
     into appt = group 
    from 
     a in appt.DefaultIfEmpty() 
    where 
     //something that narrows all combinations of events to only unique events 
    orderby 
     m.Id, 
     // something that interleaves h.DayOfMonth with m.DayOfMonth 
    select 
     new 
     { 
      Month = m.Name, 
      Holiday = h.Name, 
      HolidayDay = h.DayOfMonth, 
      Appointment = a.Description, 
      AppointmentDay = a.DayOfMonth 
     };