如何在LINQ查询中获得由2个求和字段得到的除数值?

时间:2011-06-10 19:14:50

标签: c# linq

我有以下课程:

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);

...但我不确定如何将两个字段相加然后除以得到我需要的百分比。

1 个答案:

答案 0 :(得分:2)

这应该有用......

        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);

[edit]稍微清理一下代码