【问题标题】:Grouping a LINQ query对 LINQ 查询进行分组
【发布时间】:2011-12-20 07:17:27
【问题描述】:

我有三张桌子:

  • 节目
    • 身份证
    • 姓名
  • 时间表
    • 程序 ID
    • AvailableSpots
  • 计划日期
    • ScheduleId
    • 开始日期
    • 结束日期

计划是一种事件,而计划是 ScheduleDates 的集合,因为计划会持续数天。

我希望能够显示如下列表:

// 1st is the earliest ScheduleDate and 14th is the latest. The records in between
// are ignored.
January 1-14
  Program 1    5 spots left
  Program 2    10 spots left

January 10-24
  Program 1    0 spots left

January 20-31
  Program 3    10 spots left

我需要浏览所有时间表,并按开始/结束日期对它们进行分组,以便显示该时间段内发生的所有节目。

我对 LINQ 不太熟悉,据我所知是这样的:

var schedules = from program in _db.Programs
                join schedule in _db.Schedules on program.Id equals schedule.ProgramId
                join date in _db.ScheduleDates on schedule.Id equals date.ScheduleId
                // a few where clauses
                orderby date.Startdate
                group date by date.Schedule into sch
                select sch;

我不确定这是否正确,但它确实为我提供了我的日程安排及其相关日期的分组列表,我可以通过.First.Last 获取January 1-14

不过,我不确定如何通过匹配开始/结束日期对它们进行分组,然后将匹配项下的项目分组。

【问题讨论】:

  • 所以您只想根据第一个/最后一个日期组成组?

标签: c# linq


【解决方案1】:

您可以按包含您关心的元素的匿名对象进行分组:

var schedules = from program in _db.Programs
            join schedule in _db.Schedules on program.Id equals schedule.ProgramId
            join date in _db.ScheduleDates on schedule.Id equals date.ScheduleId
            // a few where clauses
            orderby date.Startdate
            group new{Program = program, Schedule = schedule, Date = date} by new{date.Schedule.Startdate, date.Schedule.Enddate};

上面返回一个IEnumerable<IGrouping>,其中键是具有StartdateEnddate 属性(均为DateTimes)的匿名类型,元素是具有ProgramScheduleDate 元素。您可以对其进行调整以仅包含您关心的那些细节。

当用作对象时,匿名类型实现GetHasCode()Equals,如果它们的每个对应属性相等,则认为它们相等(类似于structs 的默认相等,但编译入而不是通过反射,所以它表现更好)。

与其他查询提供程序(例如 linq2sql 等)一起使用时。提供者应该意识到这一点,因此将分组传递给数据库,尽管有时它并不完美(仍然有效,但不是在数据库层完成的所有工作)。

【讨论】:

  • 呸!你是对的,我直接跳到元组并忘记了匿名类型。你有我的 +1 :-)
  • @John,谢谢,但我如何才能提取第一个和最后一个计划日期?它不会包括所有这些吗?
  • .First().Last() 在此查询中,除非我误解了您想要的结果(我可能是,我对它们并不完全清楚)。
猜你喜欢
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 2021-08-18
  • 2011-07-16
相关资源
最近更新 更多