实体框架平均,按查询分组

时间:2015-03-10 11:23:12

标签: c# asp.net-mvc entity-framework linq-to-sql linq-to-entities

您好我有以下查询

        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进行分组,然后选择mc_object,持续时间的平均值 并按平均持续时间降序排序,谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

查询应为

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