[英]Divding property by property in LINQ expression
我写了如下代码:
Session["priceRange"] = ranges.Select(r => new PriceRangeGraph
{
Price = Math.Round(r, 2),
Sales = lista.Where(x => ranges.FirstOrDefault(y => y >= x.SalePrice) == r).Sum(x => x.SaleNumber),
SuccessfulSellers = lista.GroupBy(x => x.StoreName).Where(x => ranges.FirstOrDefault(y => y >= x.Select(z => z.SalePrice).FirstOrDefault()) == r && x.Select(h => h.SaleNumber).FirstOrDefault() > 0).Count(),
UnSuccessfulSellers = lista.GroupBy(x => x.StoreName).Where(x => ranges.FirstOrDefault(y => y >= x.Select(z => z.SalePrice).FirstOrDefault()) == r && x.Select(h => h.SaleNumber).FirstOrDefault() == 0).Count(),
}).ToList();
其作用如下:
现在,我想为有销售和无销售的卖家获得成功的销售率。 我这样做的方式是:
(thoseWhoHadSales/(thoseWhoHadSales+thoseWhoDidnt))*100;
在给定的价格范围内,我将获得卖方成功销售的机会。
现在,我感到困惑的是确实发生/可能发生的异常:
Divide by zero exception... If those who had sales is equal to = 0;
现在,执行我上面显示的公式最简单的方法是什么。 我可以立即在select语句中执行此操作吗?
如果在给定价格范围内有销售量的那些人= 0,那么我只需将卖方设置为0 ...
有人可以帮我吗?
斯蒂芬,你的意思是这样的:
public double SellThroughRate
{
get { return SellThroughRate; }
set
{
if (SuccessfulSellers != 0)
{
SellThroughRate = Math.Round((SuccessfulSellers / (SuccessfulSellers + UnSuccessfulSellers)) * 100,2);
}
else
{
SellThroughRate = 0;
}
}
}
double.IsNaN()
可以替代检查等于零的条件,
double tempResult = Math.Round(((double)SuccessfulSellers / ((double)SuccessfulSellers + (double)UnSuccessfulSellers)) * 100,2);
SellThroughRate = double.IsNaN(tempResult) ? 0 : tempResult;
希望有帮助,
将您的属性设置为只读,并有条件地检查SuccessfulSellers + UnSuccessfulSellers
是否为零,以防止出现异常。 我还建议您按原样存储结果,并使用[DisplayFormat]
属性在视图中显示格式化的结果
[DisplayFormat(DataFormatString = "{0:P2}")]
public double SellThroughRate
{
get
{
double total = SuccessfulSellers + UnSuccessfulSeller;
return total == 0 ? 0 : SuccessfulSellers / total;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.