C# 实体框架 where、order 和 group
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10913396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity framework where, order and group
提问by Vivendi
I'm using the following LINQ to select data from a table:
我正在使用以下 LINQ 从表中选择数据:
(from m in entity.Results
where m.Group == 0 ||
m.Group == 1
orderby m.Points descending
select m);
This gives me a result of all Users who are in Group 1 or 2. With that i can display the points they have. But this shows me the points they have in Group 1 and Group 2 separately.
这为我提供了第 1 组或第 2 组中所有用户的结果。这样我就可以显示他们的分数。但这向我展示了他们分别在第 1 组和第 2 组中的得分。
How can i group them and display the total points they have? So instead of this (What i have now):
我如何将它们分组并显示它们的总分?所以而不是这个(我现在拥有的):
user1 - group1 - 10
user1 - group2 - 7
user2 - group1 - 7
user2 - group2 - 5
I want this:
我要这个:
user1 - total: 17
user2 - total: 12
How do i have to adjust my query to get a result set like that?
我该如何调整我的查询以获得这样的结果集?
采纳答案by david.s
You need to group the users, then use Sumto calculate the TotalPoints:
您需要对用户进行分组,然后使用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 };
回答by Asif Mushtaq
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);
回答by Sunny
Hi Vivendi use this(Please edit according to your requirement)
嗨 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);
Output
输出
total: 17
总数:17
total: 12
总数:12
回答by Cherry Blossom Girl
Another example with more than one sum and a join
另一个包含多个总和和连接的示例
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 };

