如何在LINQ查询中获得2个求和字段的分割值?
问题描述:
我有以下类:如何在LINQ查询中获得2个求和字段的分割值?
public partial class MemberTank
{
public int Id { get; set; }
public string TankName { get; set; }
public int Battles { get; set; }
public int Victories { get; set; }
}
我试图构建一个LINQ是让我TankName的列表,每个储罐的胜利百分比。我知道我需要划分战斗和胜利的总和,但我不知道该怎么做。
做一个总和或其他容易...
var sumVictories = (from p in db.MemberTanks
group p by p.TankName into g
select new {
Tank = g.Key,
Victories = g.Sum(p => p.Victories)
}).OrderByDescending(a => a.Victories);
...但我不知道如何使它总结这两个字段然后将其划分来获得我所需要的百分比。
答
这应该工作...
var sumVictories = (from p in memberTanks
group p by p.TankName
into g
select new
{
Tank = g.Key,
Victories = g.Sum(p => p.Victories),
Avg = ((double)g.Sum(p => p.Victories)/(double)g.Sum(p => p.Battles)) * 100
}).OrderByDescending(a => a.Victories);
[编辑]清理代码了相同TankName一点
能有多个MemberTank实例? – 2011-06-10 19:29:22
是的。 (我知道,数据有点不正常......虽然我可以做的并不多) – 2011-06-10 19:46:33