[英]Need help with LINQ query that joins two tables containing periodic events
我的现实生活中的例子太晦涩难解,无法解释,但这与我正在尝试做的非常相似...
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
};
这是一个使用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;
您需要在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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.