uses lambda expression to fetch data from the list:
listDatas.Sum(x => x.a / x.b)
But some x.b is zero,I try to do this,try to ignore counting data that divides by zero or null,also log error messages:
public static decimal? SumNotZero<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
{
decimal sum = 0;
foreach (TSource item in source)
{
try
{
decimal? v = selector(item);
if (v != null)
{
sum = v.GetValueOrDefault();
}
}
catch (Exception ex)
{
DoLog("The remainder is 0, and there is an error in filling in the data:" " " ex);
}
}
return sum;
}
then use the function:
listDatas.SumNotZero(x => x.a / x.b)
But always report an error: System.DivideByZeroException: Attempted to divide by zero.
CodePudding user response:
Try something like:
listDatas.Sum(x => x.A / (x.B == 0 ? 1 : x.B));
Is not a beauty code, but works.
CodePudding user response:
Just for your Information, your code should work. Maybe you need to rebuild it. However, I wouldn't use it. Only use Exceptions for real Exceptions (because they are slow). The case you have here, is realy expected.
internal static class Program
{
private static void Main(string[] args)
{
var list = new List<MyClass>
{
new MyClass(1, 0),
new MyClass(10, 5)
};
Console.WriteLine(list.SumNotZero(x => x.A / x.B));
Console.ReadKey();
}
public static decimal? SumNotZero<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
{
decimal sum = 0;
foreach (var item in source)
{
try
{
var v = selector(item);
if (v != null)
{
sum = v.GetValueOrDefault();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
return sum;
}
private class MyClass
{
public MyClass(int a, int b)
{
A = a;
B = b;
}
public int A { get; }
public int B { get; }
}
}
If I were you, I would write it this way:
listDatas.Where(x => x.b != 0).Sum(x => x.a / x.b)
Or this way:
var sum = list.Sum(x =>
{
if (x.B == 0)
{
return 0;
}
return x.A / x.B;
});
Console.WriteLine(sum);