当使用多个整数来获得捕获率时,C#LINQ除以零错误

时间:2015-02-05 22:01:59

标签: c# linq .net-4.5

您是否知道如何以零除的方式修复此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正确编译,因此我必须搞砸了。如何在这种情况下添加除以零检查?

2 个答案:

答案 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();