【问题标题】:Entity framework where, order and group实体框架 where、order 和 group
【发布时间】:2012-06-06 11:33:45
【问题描述】:

我正在使用以下 LINQ 从表中选择数据:

(from m in entity.Results
where m.Group == 0 ||
m.Group == 1
orderby m.Points descending
select m);

这为我提供了第 1 组或第 2 组中所有用户的结果。这样我可以显示他们拥有的分数。但这向我展示了他们分别在第 1 组和第 2 组中的分数。

我如何对它们进行分组并显示它们的总分?所以代替这个(我现在拥有的):

user1 - group1 - 10
user1 - group2 - 7
user2 - group1 - 7
user2 - group2 - 5

我想要这个:

user1 - total: 17
user2 - total: 12

如何调整我的查询以获得这样的结果集?

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案1】:

    您需要对用户进行分组,然后使用Sum 计算TotalPoints

    from m in entity.Results
    where m.Group == 0 || m.Group == 1
    group m by m.User into g
    let TotalPoints = g.Sum(m => m.Points)
    orderby TotalPoints descending
    select new { User = g.Key, Username = g.Key.Username, TotalPoints };
    

    【讨论】:

    • 这似乎有效。但我也想在结果中包含用户名。所以在 select new { ... } 部分我尝试添加这个 --- g.First().User.Username。但这似乎不起作用。知道如何包含用户名吗?
    • @Vivendi 您已经选择了User,您不需要更改查询。或者你可以这样做`select new { User = g.Key, Username = g.Key.Username, TotalPoints };
    【解决方案2】:
    entity.Results
          .Where(m => m.Group == 0 || m.Group == 1)
          .GroupBy(m => m.UserID)
          .Select(m => new { User = m.Key, TotalPoints = m.Sum(v => v.Points) })
          .OrderByDescending(m => m.TotalPoints);
    

    【讨论】:

    • 非常感谢。它帮助了我。
    【解决方案3】:

    你好 Vivendi 使用这个(请根据你的要求编辑)

    var q = (from h in entity.Results
    group h by new { h.UserID} into hh
    select new {
        hh.Key.UserID,
        Score = hh.Sum(s => s.Points )
    }).OrderByDescending(i => i.Points);
    

    输出

    总数:17

    总数:12

    【讨论】:

      【解决方案4】:

      另一个有多个总和和一个连接的例子

       from e in _context.LearnResults
       join c in _context.Country on e.CountryId equals c.CountryId
       where c.DomainId.Equals("xx")
       group e by e.Country.Name into newCountry
       let Approved = newCountry.Sum(e => e.Approved)
       let Total = newCountry.Sum(e => e.Total)
       select new LearnResults() { CountryName = newCountry.Key, Approved= Approved, Total=Total };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-06
        • 1970-01-01
        • 2013-02-02
        • 2011-12-31
        • 1970-01-01
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        相关资源
        最近更新 更多