本文介绍了使用重复参数优化可枚举的LINQ WHERE语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code to return all records that has the contract expiration in determined days:

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语句是什么?

As you can see, q.StaffContracts.OrderByDescending(p => p.SignedDate).FirstOrDefault() is repeated many times. Is there a way to shorten this statement? And what is its equivalence SQL statement?

推荐答案

这种方式怎么样?

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;

这篇关于使用重复参数优化可枚举的LINQ WHERE语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 21:25