Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对LINQ查询进行分组_C#_Linq - Fatal编程技术网

C# 对LINQ查询进行分组

C# 对LINQ查询进行分组,c#,linq,C#,Linq,我有三张桌子: 节目 身份证 名字 时间表 程序ID 有效点 时间表日期 调度ID 起始日期 结束日期 程序是一种事件类型,日程表是日程表日期的集合,因为程序在几天内进行 我希望能够显示如下列表: // 1st is the earliest ScheduleDate and 14th is the latest. The records in between // are ignored. January 1-14 Program 1 5 spots left P

我有三张桌子:

  • 节目
    • 身份证
    • 名字
  • 时间表
    • 程序ID
    • 有效点
  • 时间表日期
    • 调度ID
    • 起始日期
    • 结束日期
程序是一种事件类型,日程表是日程表日期的集合,因为程序在几天内进行

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

// 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;

我不确定这是否正确,但它确实为我提供了一个时间表及其相关日期的分组列表,我可以先执行
。然后执行
。最后执行
以获取
1月1日至14日的日期


但是,从这里开始,我不确定如何通过匹配开始/结束日期对它们进行分组,然后在匹配项下对项目进行分组。

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

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
,其中键是一个匿名类型,具有
Startdate
Enddate
属性(都是
DateTime
s),元素是带有
Program
Schedule
Date
元素的匿名类型。您可以对此进行调整,使其仅包含您关心的那些细节

当用作对象时,匿名类型实现一个
GetHasCode()
Equals
,如果它们对应的每个属性都相等,则认为它们相等(类似于
struct
s的默认相等,但在中编译而不是通过反射,因此性能更好)


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

所以您只想根据第一个/最后一个日期组成组?呸!你说得对,我直接跳到元组,忘记了匿名类型。你有我的+1:-)@John,谢谢,但是我怎样才能完成第一个和最后一个计划日期呢?它不包括所有这些吗?
.First()
.Last()
在这个查询中,除非我不理解您想要的结果(我可能是,我对它们不完全清楚)。