我的现实生活中的例子太难以解释,但这是我正在尝试做的很好的近似...
Month
表格包含以下列:Id
,Name
Holiday
表包含以下列:Id
,MonthId
,DayOfMonth
,Name
Appointment
表包含以下列:Id
,MonthId
,DayOfMonth
,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 :(得分: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;
答案 1 :(得分:0)
你需要在SQL中进行LEFT OUTER连接,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
};