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
精彩评论