C#MVC中的Linq百分比

hnc*_*ncl 1 c# linq-to-sql

我正在使用带有c#的MVC3,我试图从我的模型中获得以下百分比:

我检索数字:

 ... 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
Run Code Online (Sandbox Code Playgroud)

我需要划分:

百分比=计数/总计*100

我不知道如何在Linq格式化这个.

Cod*_*mmy 6

首先需要强制转换decimaldouble避免整数除法.在乘以100并进行舍入后,您需要转回int.

另一方面,Count()s 的强制转换int是无用的,Count()已经返回一个整数.

int count = g.Count();
int total = ctx.vw_MasterViews.Count();
int percent = (int)Math.Round((Decimal)count/(Decimal)total*100, MidpointRounding.AwayFromZero);
Run Code Online (Sandbox Code Playgroud)