0

我现实生活中的例子太晦涩无法解释,但这是我正在尝试做的一个很好的近似......

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
        };
4

2 回答 2

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;
于 2009-09-11T00:00:11.353 回答
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
        };
于 2009-09-10T20:08:40.557 回答