我写了如下代码:
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;
}
}
}
答案 0 :(得分:1)
double.IsNaN()
可以替代检查等于零条件,
double tempResult = Math.Round(((double)SuccessfulSellers / ((double)SuccessfulSellers + (double)UnSuccessfulSellers)) * 100,2);
SellThroughRate = double.IsNaN(tempResult) ? 0 : tempResult;
希望有所帮助,
答案 1 :(得分:1)
使您的属性只读,并有条件地检查SuccessfulSellers + UnSuccessfulSellers
是否为零以防止异常。我还建议您按原样存储结果,并使用[DisplayFormat]
属性在视图中显示格式化结果
[DisplayFormat(DataFormatString = "{0:P2}")]
public double SellThroughRate
{
get
{
double total = SuccessfulSellers + UnSuccessfulSeller;
return total == 0 ? 0 : SuccessfulSellers / total;
}
};