Entity framework 平均值,按查询分组

Entity framework average , group by query

您好,我有以下问题

        var myList = (from p in db.Full
                      where (p.date_reception > begin & p.date_reception < end & !p.mc_object.Contains("NULL")
                             & (!strListe.Contains(p.mc_object)))
                      group p by new { p.mc_object} into g

                      select g.OrderByDescending(p => new {p.duration,p.mc_object} ) into r
                      select new StringIntType
                      {
                          str = r.mc_object,
                          nbr = r.duration.Value
                      }).Take(50).ToList();

我需要按 mc_object 和 select mc_object 分组,平均持续时间 并按平均持续时间降序排列,感谢您的帮助

查询应该是

var myList = (from p in db.Full

              // Don't use &! Use &&
              where p.date_reception > begin && 
                    p.date_reception < end && 
                    !p.mc_object.Contains("NULL") && 
                    !strListe.Contains(p.mc_object)

              group p by p.mc_object into g

              select new 
              { 
                  mc_object = g.Key, 
                  /* data = g, */
                  avg = g.Average(x => x.duration) 
              } into h

              // if you want both descending, add descending after mc_object
              orderby h.avg descending, h.mc_object 

              select new StringIntType
              {
                  str = h.mc_object,
                  nbr = (int)h.avg // Average returns a double
              }).Take(50).ToList();
        }

请注意,我已将 & 更改为 &&。对于订购我不确定。我不需要查询后半部分的完整数据,所以我添加了注释 data = g