Linq-优化/更正我的查询

本文关键字:我的 查询 优化 Linq- | 更新日期: 2023-09-27 18:21:55

我有这个linq查询(不确定它是否正确),但我想要的是:

给我我所有的公司办公室(与我的公司有关,例如companyid==mycompanyid)声明他们有邮政编码"cv"的,只返回办公室。(清晰代码)

var offices = from office in _readOnlySession.All<Office>()
.GetMyOffices(_userSession) //filter out my offices using extension method
let postcodes = _readOnlySession.All<OfficePostCode>().Where(x => x.OfficeID == office.OfficeID)
                .Join(_readOnlySession.All<PostCodeDistrict>().Where(r=> r.Region.ToLower().StartsWith("cv".ToLower())),
                          x => x.PostCodeID,
                          y => y.PostCodeID,
                          (x, y) => new { Region = y.Region })
where postcodes.Any()
select new { office.OfficeID, office.Name };

问题:我如何使这一切成为一种查询方法,一种更优化/更正确的查询方法?

注意:"cv"将是一个传递到方法中的变量-有点硬编码,以说明我的示例

更新:

    IQueryable<T> All<T>() where T : class, new();
    public IQueryable<T> All<T>() where T : class, new()
    {
        return GetTable<T>().AsQueryable();
    }

Linq-优化/更正我的查询

我假设OfficePostCodeOffice都有PostCodeID属性,您可能需要更改最后一个.Where()子句以适应您的属性。不过,这应该是你想要的,IMO更容易阅读。

public IEnumerable<Office> GetOffices (string postCode)
{
    List<Office> myOffices = _readOnlySession.All<Office> ()
        .GetMyOffices (_userSession)
        .ToList (); // Get all the offices you are interested in.

    List<OfficePostCode> postCodeDistricts = _readOnlySession
        .All<OfficePostCode> ()
        .Where (x => x.Region.StartsWith (postCode, true, System.Globalization.CultureInfo.InvariantCulture))
        .ToList (); // A list of OfficePostCodes with the specified region.
    // Using the 3 parameter overload for StartsWith lets you specify a case invariant comparison,
    // which saves you from having to do .ToLower().
    return myOffices.Where (o => postCodeDistricts.Any (pcd => o.PostCodeID == pcd.PostCodeID));
}

当然,你可以通过删除中间变量来压缩它,但我个人觉得这样更清楚。它也使调试更容易,因为您可以在中间变量上设置断点。

这似乎还可以。只有在主查询之前执行let postcode部分而不带OfficeID条件,然后在主查询中使用它,如:

where postcodes.Any(pc => pc.OfficeID == office.OfficeID)

可能是这样的吗?

var offices = _readOnlySession.All<Office>()
    .GetMyOffices(_userSession) //filter out my offices using extension method
    .Where(office => office.PostCodes.Any(pc => pc.District.Region.ToUpperInvariant().StartsWith("CV")));