Reputation: 2295
I am using MVC3 with c# and I'm trying to get the percentage from the following in my model:
I retrieve the numbers:
... Code omitted
AgeGroup = g.Key.AgeGroup,
Count = (int)g.Count(),
Total = (int)
(from vw_masterview0 in ctx.vw_MasterViews
select new
{
vw_masterview0.ClientID
}).Count()
... Code omitted
I need to divide:
percent = Count/Total * 100
I have no idea how to format this in Linq.
Upvotes: 1
Views: 1536
Reputation: 61
You first need to cast to decimal
or double
to avoid integer division. After multiplying with 100 and rounding, you need to cast back to int
.
The casts of the Count()
s to int
on the other hand are useless, Count()
already returns an integer.
int count = g.Count();
int total = ctx.vw_MasterViews.Count();
int percent = (int)Math.Round((Decimal)count/(Decimal)total*100, MidpointRounding.AwayFromZero);
Upvotes: 6