c# MVC中的Linq百分比
本文关键字:百分比 Linq 中的 MVC | 更新日期: 2023-09-27 18:13:54
我正在使用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
我需要除:
percent = Count/Total * 100
我不知道如何在Linq中格式化这个
首先需要转换为decimal
或double
以避免整数除法。在乘以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);