开发者

How can I get a divided value resulting from 2 summed fields in a LINQ query?

开发者 https://www.devze.com 2023-03-12 15:58 出处:网络
I have the following class: public partial class MemberTank { public int Id { get; set; } public string TankName { get; set; }

I have the following class:

public partial class MemberTank
{
    public int Id { get; set; }
    public string TankName { get; set; }
    public int Battles { get; set; }
    public int Victories { get; set; }
}

I am trying to construct a LINQ that gets me a list of TankName with the victory percentage of each tank. I know I need to divide the sums of both battles and victories but I'm not sure how to do that.

Doing the sum of one or the other is easy ...

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

... but I'm not sure how to make it sum both fields then divide them to get the percentage I n开发者_开发百科eed.


This should work...

        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] Cleaned the code up a little

0

精彩评论

暂无评论...
验证码 换一张
取 消