同一Lambda中2个值的总和?

Sum of 2 values in same lambda?
2021-02-23
  •  译文(汉语)
  •  原文(英语)

我有以下LINQ查询,在其中我必须将分隔.Sum成单独的调用,当我将它们组合时得到一个NaN.这不起作用:

var rejectRate = (results.Sum(x => x.TraysRejectedDay / x.TraysProcessedDay)) * 100;

这确实有效:

var traysProcessed = results.Sum(x => x.TraysProcessedDay);
var rejectRate = (results.Sum(x => x.TraysRejectedDay / traysProcessed)) * 100;

这仅仅是对LINQ的限制,还是我做错了什么?这两个字段的数据类型相同(double)

速聊1:
那是两个不同的查询.前者将所有内容TraysRejectedDay相除TraysProcessedDay并返回总和.后者将所有TraysRejectedDay数相除,TraysProcessedDay然后返回总和.可以TraysProcessedDay为零吗?
解决过程1

那是两个不同的查询.前者将所有内容TraysRejectedDay相除TraysProcessedDay并返回总和.后者将所有TraysRejectedDay数相除,TraysProcessedDay然后返回总和.

因此TraysProcessedDay,例如,如果可以为0,则除以零.也许您想忽略它们:

var rejectRate = (results
    .Where(x => x.TraysProcessedDay > 0)
    .Sum(x => x.TraysRejectedDay / x.TraysProcessedDay)) * 100;
速聊1:
DivideByZeroException不是给一个代替NaN吗?
速聊2:
来自MSDN的文章:"当操作的结果未定义时,方法或运算符将返回NaN.例如,零除以零的结果为NaN,..."

I have the following LINQ query where I am having to seperate the .Sum into seperate calls, when I combine them I get an NaN. This doesn't work:

var rejectRate = (results.Sum(x => x.TraysRejectedDay / x.TraysProcessedDay)) * 100;

This does work:

var traysProcessed = results.Sum(x => x.TraysProcessedDay);
var rejectRate = (results.Sum(x => x.TraysRejectedDay / traysProcessed)) * 100;

Is this just a limitation of LINQ or am I doing something wrong? Both of the fields are the same data type (double)

Talk1:
Those are two different queries. The former divides every TraysRejectedDay through TraysProcessedDay and returns the sum. The latter divides every TraysRejectedDay through the sum of all TraysProcessedDay and returns the sum. Can TraysProcessedDay be zero?
Solutions1

Those are two different queries. The former divides every TraysRejectedDay through TraysProcessedDay and returns the sum. The latter divides every TraysRejectedDay through the sum of all TraysProcessedDay and returns the sum.

So if TraysProcessedDay for example can be 0 you'd divide through zero. Maybe you want to ignore them:

var rejectRate = (results
    .Where(x => x.TraysProcessedDay > 0)
    .Sum(x => x.TraysRejectedDay / x.TraysProcessedDay)) * 100;
Talk1:
Wouldn't that give a DivideByZeroException instead of NaN?
Talk2:
: from MSDN: "A method or operator returns NaN when the result of an operation is undefined. For example, the result of dividing zero by zero is NaN, ..."
转载于:https://stackoverflow.com/questions/23733530/sum-of-2-values-in-same-lambda

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入