linq-to-sql分组匿名类型

时间:2012-07-20 16:30:36

标签: c# linq-to-sql

我有一张包含约会的表格。这些约会具有不同的状态(字节从1到5)和日期;日期的列简称为AppointDate。我传入了一个ID列表,我想根据状态以及约会的日期是否过去来对结果进行分组。

TheIDs是作为参数传入的long列表。这就是我到目前为止所做的:

var TheCounterInDB = (from a in MyDC.Appointments
                      where TheIDs.Contains(a.ID)
                      group a by a.AppointStatus into TheGroups
                      select new { 
                             TheStatus = TheGroups.Key,
                             TheTotalCount = TheGroups.Count(),
                             TheLateCount = ?,
                             ThePendingCount = ?
                      }).ToList();

基本上,我希望TheLateCount是所有约会的计数,其中状态为1且日期已过,ThePendingCount为状态为1且日期未过去的计数。我的匿名类型可以返回所有不同状态的计数(这是.Key所在的位置),但我想知道如何最好地将日期要求添加到分组中。

感谢您的建议。

1 个答案:

答案 0 :(得分:4)

var TheCounterInDB = (from a in MyDC.Appointments
                      where TheIDs.Contains(a.ID)
                      group a by a.AppointStatus into TheGroups
                      select new { 
                             TheStatus = TheGroups.Key,
                             TheTotalCount = TheGroups.Count(),
                             TheLateCount = TheGroups.Count(x => x.AppointStatus == 1 && x.AppointDate < DateTime.Today),
                             ThePendingCount = TheGroups.Count(x => x.AppointStatus == 1 && x.AppointDate >= DateTime.Today)
                      }).ToList();