使用重复参数优化可枚举的 LINQ WHERE 语句



我有以下代码返回合同在确定日期到期的所有记录:

return pSource
                .Where(q => 
                    q.StaffContracts.OrderByDescending(p => p.SignedDate).FirstOrDefault().Timespan.HasValue &&
                    q.StaffContracts.OrderByDescending(p => p.SignedDate).FirstOrDefault().SignedDate.HasValue &&
                    (q.StaffContracts.OrderByDescending(p => p.SignedDate).FirstOrDefault().SignedDate.Value.AddMonths( q.StaffContracts.OrderByDescending(p => p.SignedDate).FirstOrDefault().Timespan.Value)
                    - now).TotalDays <= value);

如您所见,q.StaffContracts.OrderByDescending(p => p.SignedDate).FirstOrDefault()重复了很多次。有没有办法缩短这个陈述?它的等效 SQL 语句是什么?

这样做怎么样?

return
    from q in pSource
    let sc = q.StaffContracts
        .OrderByDescending(p => p.SignedDate)
        .FirstOrDefault()
    where sc != null
    let ts = sc.Timespan
    let sd = sc.SignedDate
    where ts.HasValue
    where sd.HasValue
    where (sd.Value.AddMonths(ts.Value) - now).TotalDays <= value
    select q;
你可以

把它变成一个方法体......它返回bool。检查null可能也不是一个坏主意:

return pSource.Where(q => {
    var contract = q.StaffContracts.OrderByDescending(p => p.SignedDate).FirstOrDefault();
    if (contract == null)
        return false; // returns nothing
    return contract.Timespan.HasValue &&
           contract.SignedDate.HasValue &&
           (contract.SignedDate.Value.AddMonths(contract.Timespan.Value) - now)
           .TotalDays <= value;
});

我要冒昧地说,这会大大提高你的表现......只有一个订单调用。

最新更新