2011-11-09 172 views
1

我使用MVC3用C#,我想从我的模型如下比例:LINQ的百分比

我找回号码:

... 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 

我需要划分:

百分率为计数/总* 100

我不知道如何在LINQ to格式化这个。

回答

6

首先需要转换为decimaldouble避免整数除法。用100乘以四舍五入以后,你需要转换回int

另一方面,Count()的演员阵容到int都没用,Count()已经返回一个整数。

int count = g.Count(); 
int total = ctx.vw_MasterViews.Count(); 
int percent = (int)Math.Round((Decimal)count/(Decimal)total*100, MidpointRounding.AwayFromZero); 
+0

谢谢,现在我得到这个错误:对于转换为SQL时,Math.Round方法需要MidpointRounding参数。使用'AwayFromZero'来指定SQL函数ROUND。 – hncl

+0

然后做什么它说。我已经更新了我的答案,以包含舍入模式。我怀疑这是因为SQL不支持银行家的圆,这是默认的舍入。 –