Med*_*tor 6 c# linq divide-by-zero
ads = ads.Where(x => (x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);
Run Code Online (Sandbox Code Playgroud)
如果x.Amount == 0我有错误"遇到零除错误".
喜欢我在这个要求是避免?
更新:
这有帮助,但我不喜欢这个决定:
ads = ads.Where(x => (x.Amount - x.Price) / ((x.Amount / 100)==0?0.1:(x.Amount / 100)) >= filter.Persent);
Run Code Online (Sandbox Code Playgroud)
还有另外一种方法吗?
Jul*_*bre 24
当然,您始终可以实现通用的安全除法方法并一直使用它
using System;
namespace Stackoverflow
{
static public class NumericExtensions
{
static public decimal SafeDivision(this decimal Numerator, decimal Denominator)
{
return (Denominator == 0) ? 0 : Numerator / Denominator;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我选择了十进制类型,因为它解决了我所知道的所有非可空数字类型.
用法:
var Numerator = 100;
var Denominator = 0;
var SampleResult1 = NumericExtensions.SafeDivision(Numerator , Denominator );
var SampleResult2 = Numerator.SafeDivision(Denominator);
Run Code Online (Sandbox Code Playgroud)
Jon*_*Jon 10
ads = ads.Where(x => x.Amount != 0 &&
(x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19273 次 |
| 最近记录: |