linq group by statement

时间:2011-01-19 21:49:28

标签: c# linq

我有一个包含日期的对象MyObject。 我有以下查询,其中TheMonth和TheYear是参数:

var MyQuery = from a in MyModelDC.MyTable
              where a.Month == TheMonth
              where a.Year == TheYear
              select new MyObject
                   {

                        var1 = a.Day,

                        var2 = (from b in MyModel.MyTable
                                where b.Month == a.Month
                                where b.Year == a.Year
                                select b.Identity).Count()
                    };

我想将结果分组,以便每天只发生一次。 Var 2是一个计数,此时,每次出现Identity时都会重复计数行,而不是每天唯一。

感谢。

1 个答案:

答案 0 :(得分:3)

如果我正确理解您的要求,我认为这将按照您的要求行事:

var myQuery = from date in MyModelDC.MyTable
              where date.Month == TheMonth && date.Year == TheYear
              group date by date.Day into dayGroup
              select new
              {
                  Day = dayGroup.Key,
                  Count = dayGroup.Count()
              };

这里我们首先按照引用的日期对每个项目进行分组,然后我们计算组中的每个项目,以便我们只包含该组特定日期的项目。

<强>更新
要使用MyObject作为输出,您可以执行以下操作:

var myQuery = from date in MyModelDC.MyTable
              where date.Month == TheMonth && date.Year == TheYear
              group date by date.Day into dayGroup
              select new MyObject
              {
                  var1 = dayGroup.Key,
                  var2 = dayGroup.Count()
              };