尝试执行连接两个表的linq查询,具有where子句,并对结果进行分组

时间:2012-08-23 22:29:22

标签: sql-server linq linq-to-sql

我确信这很简单,但我无法让它发挥作用。这是我用作我的参考的SQL查询。我想用LINQ做同样的事情。

SQL:

select
schedulegroupslist.Schedule_Group_Key,
schedulegroupslist.Group_Name
from schedulegroupslist
inner join schedules on schedules.schedule_group_key = schedulegroupslist.Schedule_Group_Key
where schedules.Active = 1
and schedulegroupslist.Schedule_Count > 0
and schedulegroupslist.Active = 1
group by schedulegroupslist.Schedule_Group_Key
,schedulegroupslist.Group_Name

这是我认为可以解决问题的linq,但我在组计划行上获得了一个空引用异常。

LINQ:

var included = from g in allGroups
           join s in allSchedules 
           on g.ScheduleGroupKey equals s.GroupKey into sg
           from schedules in sg.Where(s => s.Active == true 
                                           && g.ScheduleCount > 0 
                                           && g.Active == true).DefaultIfEmpty()
           group schedules by 
                    new { schedules.Key, schedules.ScheduleGroupName } 
                    into schedulesgroup
           select new { GroupName = schedulesgroup.Key.ScheduleGroupName,
                        ScheduleGroupKey = schedulesgroup.Key.Key };

对linq不太流利,所以也许有人可以告诉我一个更好的方法来完成我正在做的事情?

2 个答案:

答案 0 :(得分:1)

试试这个:

var included = from g in allGroups
               join s in allSchedules on g.ScheduleGroupKey equals s.GroupKey
               where s.Active && g.ScheduleCount > 0 && g.Active
               group s by new { s.Key, s.ScheduleGroupName } into grp
               select new
               {
                   ScheduleGroupKey = grp.Key.Key,
                   GroupName = grp.Key.ScheduleGroupName,
               };

我认为在这种情况下分组是没用的,所以这可能会更好:

var included = from g in allGroups
               join s in allSchedules on g.ScheduleGroupKey equals s.GroupKey
               where s.Active && g.ScheduleCount > 0 && g.Active
               select new
               {
                   ScheduleGroupKey = s.Key,
                   GroupName = s.ScheduleGroupName,
               };

答案 1 :(得分:0)

var included = from g in allGroups
           join s in allSchedules on g.ScheduleGroupKey equals s.GroupKey
           where s.Active == true 
                 && g.ScheduleCount > 0 
                 && g.Active == true
           group g by new { g.ScheduleGroupKey, g.ScheduleGroupName } into gr
           select new 
           {
               gr.Key.ScheduleGroupKey,
               gr.Key.ScheduleGroupName
           }