linq:具有多个可空类型的groupby

时间:2011-03-09 22:32:45

标签: c# linq

我有下表:

| AppointID | UserID | AppointSet | AppointAttended | AppointCancelled | AppointRescheduled |
|     1     |   1    |  2/15/2011 |                 |   3/11/2011      |                    |
|     2     |   1    |  2/17/2011 |                 |                  |    3/11/2011       |
|     3     |   1    |  3/11/2011 |   3/11/2011     |                  |                    |
|     4     |   1    |  3/10/2011 |                 |   3/11/2011      |                    

|

我要做的是创建以下输出,按日计算活动。

|    Date     |   Set   |   Attended   |   Rescheduled   |   Cancelled   |
|  3/10/2011  |    1    |              |                 |               |
|  3/11/2011  |    1    |      1       |       1         |      2        |

请注意,我已将字段AppointAttended,AppointCancelled和AppointRescheduled定义为可为空,因为可能没有这些日期。

这就是我到目前为止所做的事情,我正在与groupby进行斗争,因为我需要按多列进行分组,而且它是一个可以为空的类型,我无法让.Key工作!换句话说,我觉得我真的很难受:

var OutputMonthlyActivity = from appnt in MyDC.LeadsAppointments
where appnt.UserID == TheUserID
where (appnt.AppointSet.Month == TheDate.Month && appnt.AppointSet.Year == TheDate.Year) ||
(appnt.AppointAttended.Value.Month == TheDate.Month && appnt.AppointAttended.Value.Year == TheDate.Year) ||
(appnt.AppointRescheduled.Value.Month == TheDate.Month && appnt.AppointRescheduled.Value.Year == TheDate.Year) ||
(appnt.AppointCancelled.Value.Month == TheDate.Month && appnt.AppointCancelled.Value.Year == TheDate.Year)
group appnt by new { appnt.AppointSet, appnt.AppointRescheduled, appnt.AppointAttended, appnt.AppointCancelled } into daygroups
where daygroups.Count() > 1
select new ViewMonthlyActivityModel()
{

ViewDate = daygroups.Key,

CountTotalSetOnDay = (from c in daygroups
where c.AppointSet.Date == daygroups.Key
select c.AppointID).Count(),

TheDate是一个日期时间,它作为参数传递,代表查询的月份的第一天:例如3月的3月1日。

我在groupby语句中得到“匿名类型不能具有多个具有相同名称的属性”,并且.Key不起作用,因此按日分组不起作用。

如果您有任何建议,我们将非常感激。

感谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试显式设置您所分组的匿名类型属性的正确名称:

group appnt by new {
                     Set = appnt.AppointSet,
                     Rescheduled = appnt.AppointRescheduled,
                     Attended = appnt.AppointAttended,
                     Cancelled = appnt.AppointCancelled } into daygroups