【问题标题】:linq groupby questionlinq groupby 问题
【发布时间】:2011-06-12 05:21:45
【问题描述】:

我有一个包含几列的表:HarvestID、HarvestDate、UserID 来提及主要的列。 对于每个日期,每天都会有多个 HarvestID。

到目前为止,我有以下 linq 查询:

TheUserID 和 TheMonth 作为 int 和 DateTime 传入

var MyQuery = from h in MyDC.HarvestTable
              where h.UserID == TheUserID
              where h.HarvestDate.Month == TheMonth.Month
              where h.HarvestDate.Year == TheMonth.Year
              group h by h.HarvestDate.Day into TheDays
              from d in TheDays
              select new
              {
                  TheDay = d.HarvestDate.Date,
                  TheDayCount = (from c in TheDay
                                 select c.HarvestID).Count()
              };

我希望输出是每天计数的列表。查询没有错误,但问题是目前查询没有返回每天的唯一行。分组不起作用,我不知道为什么。这段代码有什么问题?

谢谢。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    它认为您的查询应该是

    var MyQuery = from h in MyDC.HarvestTable
                  where h.UserID == TheUserID
                  where h.HarvestDate.Month == TheMonth.Month
                  where h.HarvestDate.Year == TheMonth.Year
                  group h by h.HarvestDate.Day into TheDays
                  select new
                  {
                      TheDay = TheDays.Key,
                      TheDayCount = TheDays.Count()
                  };
    

    这是对上述分组声明http://msdn.microsoft.com/en-us/vcsharp/aa336754.aspx#simple1的一个很好的参考

    【讨论】:

    • 问题在于 TheDay 是一个日期时间。我试过 (DateTime)TheDays.Key 但演员表不起作用。
    • 我明白了。 TheDay 是一个日期,它与 Key 无关。我刚刚删除了该行并将其替换为 TheDay = (from c in TheDay select c.Date).First();这句话以后会不会给我带来麻烦?
    • TheDays.Key 是一个 Integer,因为 DateTime.Day 返回一个 Integer,表示月份中的某天
    • 您应该通过 TheDay = new DateTime(TheMonth.Year,TheMonth.Month,TheDays.Key) 创建一个新日期
    • 好的,感谢您的澄清;你让我走上了正确的道路。
    【解决方案2】:
    var MyQuery = from h in MyDC.HarvestTable
                  where h.UserID == TheUserID
                  && h.HarvestDate.Month == TheMonth.Month
                  && h.HarvestDate.Year == TheMonth.Year
                  group h by h.HarvestDate.Day into g
                  select new
                  {
                      TheDay = g.Key,
                      TheDayCount = g.Count()
                  };
    

    这不会在没有数据的日子给你零 - 但应该给你一个计数。

    http://msdn.microsoft.com/en-us/vcsharp/aa336746 是 LINQ 示例的首选页面。

    【讨论】:

    • 问题在于 TheDay 是一个日期时间。我试过 (DateTime)TheDays.Key 但演员表不起作用。
    • 我明白了。 TheDay 是一个日期,它与 Key 无关。我刚刚删除了该行并将其替换为 TheDay = (from c in TheDay select c.Date).First();这句话以后会不会给我带来麻烦?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    相关资源
    最近更新 更多