2011-11-09 171 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不支持銀行家的圓,這是默認的舍入。 –