ads = ads.Where(x => (x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);
如果x.Amount == 0我有错误“遇到零除错误。”
像我这样的请求是避免吗?更新
这有帮助,但我不喜欢这个决定:
ads = ads.Where(x => (x.Amount - x.Price) / ((x.Amount / 100)==0?0.1:(x.Amount / 100)) >= filter.Persent);
还有另一种方法吗?
答案 0 :(得分:20)
当然,您始终可以实现通用的安全分区方法并一直使用
using System;
namespace Stackoverflow
{
static public class NumericExtensions
{
static public decimal SafeDivision(this decimal Numerator, decimal Denominator)
{
return (Denominator == 0) ? 0 : Numerator / Denominator;
}
}
}
我选择了十进制类型,因为它解决了我所知道的所有非可空数字类型。
用法:
var Numerator = 100;
var Denominator = 0;
var SampleResult1 = NumericExtensions.SafeDivision(Numerator , Denominator );
var SampleResult2 = Numerator.SafeDivision(Denominator);
答案 1 :(得分:10)
ads = ads.Where(x => x.Amount != 0 &&
(x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);