您是否知道如何以零除的方式修复此LINQ问题。
我有一个对象列表,它列出了报价未完成的各种原因,并尝试按捕获率排序。
int NoOfQuotes //this is the number of quotes
int NoOfQuotesBooked //these quotes completed
int DuplicateQuotes //these are duplicate quotes that we don't want to count.
捕获率为NoOfQuotesBooked / (NoOfQuotes - DuplicateQuotes).
如果NoOfQuotes - DuplicateQuotes == 0
,则应该返回0.0
进行排序。
_customerSummaryItems = _customerSummaryItems.OrderByDescending(x => (x.NoOfQuotesBooked / (x.NoOfQuotes - x.DuplicateQuotes)))
.ThenBy(x => x.CompanyName)
.ThenBy(x => x.FirstName)
.ThenBy(x => x.LastName)
.ToList();
无论我如何尝试和排序,我都无法让Linq正确编译,因此我必须搞砸了。如何在这种情况下添加除以零检查?
答案 0 :(得分:3)
所以只需检查结果并进行计算:
_customerSummaryItems = _customerSummaryItems
.OrderByDescending(x => x.NoOfQuotes - x.DuplicateQuotes != 0
? (x.NoOfQuotesBooked / (x.NoOfQuotes - x.DuplicateQuotes)))
: 0.0)
.ThenBy(x => x.CompanyName)
.ThenBy(x => x.FirstName)
.ThenBy(x => x.LastName)
.ToList();
答案 1 :(得分:1)
似乎你想要:
_customerSummaryItems = _customerSummaryItems
.OrderByDescending(x =>
x.NoOfQuotes == x.DuplicateQuotes
? 0.0
: (x.NoOfQuotesBooked / (x.NoOfQuotes - x.DuplicateQuotes)))
.ThenBy(x => x.CompanyName)
.ThenBy(x => x.FirstName)
.ThenBy(x => x.LastName)
.ToList();