LINQ查询需要在WHERE子句中使用条件操作数

时间:2017-05-19 21:53:35

标签: c# linq comparison-operators operands

我无法编写LINQ语句,该语句在where子句中使用条件操作数,并且在没有任何运气的情况下查看了此站点中的类似问题。我确信有更好的方法来表达这个查询。其中的值XXX是确定要用于比较的对象中的哪个字段的结果,并在下面进行说明。

以下是我想要完成的事情:

var paymentReceivedAmt = (from registerEntry in RegisterEntries
    where registerEntry.TransactionType != null
    && registerEntry.TransactionType.Id.SubsystemCode == "A"
    && registerEntry.Receipt != null
    && registerEntry.PostDate != null
    && XXX >= lastInvoicedDate
    select registerEntry.TransactionAmount.GetValueOrDefault(0)).Sum();

XXX =

if registerEntry.AddedDate = registerEntry.PostDate
    registerEntry.AddedDate
else
    registerEntry.PostDate

registerEntry.AddedDateregisterEntry.PostDate是DateTime类型,但是在比较时我只需要比较日期而不是时间

有没有人知道如何做到这一点?

2 个答案:

答案 0 :(得分:3)

为什么不将registerEntry.PostDate用于XXX?如果它等于registerEntry.AddedDate,也可以使用它并简化整个事情

var paymentReceivedAmt = (from registerEntry in RegisterEntries
    where registerEntry.TransactionType != null
    && registerEntry.TransactionType.Id.SubsystemCode == "A"
    && registerEntry.Receipt != null
    && registerEntry.PostDate != null
    && registerEntry.PostDate >= lastInvoicedDate
    select registerEntry.TransactionAmount.GetValueOrDefault(0)).Sum();

答案 1 :(得分:0)

根据您使用的LINQ提供程序,您可以尝试ternary operator

var paymentReceivedAmt = (from registerEntry in RegisterEntries
    where registerEntry.TransactionType != null
    && registerEntry.TransactionType.Id.SubsystemCode == "A"
    && registerEntry.Receipt != null
    && registerEntry.PostDate != null
    && (registerEntry.AddedDate == registerEntry.PostDate
            ? registerEntry.AddedDate
            : registerEntry.PostDate) >= lastInvoicedDate
    select registerEntry.TransactionAmount.GetValueOrDefault(0)).Sum();