实体框架,其中、顺序和组
本文关键字:顺序 其中 框架 实体 | 更新日期: 2023-09-27 18:36:20
我使用以下 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
如何调整查询才能获得这样的结果集?
您需要对用户进行分组,然后使用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 };
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);
嗨维
条旺迪使用这个(请根据您的要求编辑)
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
另一个具有多个总和和一个连接的示例
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 };