我可以使用相同的Linq代码查询不同的条件吗?

时间:2013-10-12 15:32:19

标签: linq where-clause dry

我每次重复以下linq代码,其中WHERE部分略有不同。

我想遵循DRY原则,只指定一次View Model。有没有办法重用相同的查询并动态指定WHERE条件?

我在这里看了一眼,并遇到了一些类似的问题,但我找不到对我有意义的答案。我错过了一些明显的东西吗?

第一个例子

List<CMSSummary> summaryList = db.CMSUpdates
    .Where(i => i.PublishDate.Year == year)  // only this line is different
    .AsEnumerable().Select(i => new CMSSummary
    {
        CMSObjectID = i.CMSObjectID,
        Title = i.Title,
        SubTitle = i.PublishDate.ToString("ddd dd MMM"),
        ToolTip = i.Title,
        Summary = i.Summary,
        MainImage = i.MainImage,
        ItemURL = i.URL,
        FullURL = "/mockup/cmspage/" + i.URL,
        HTMLClasses = ""
    }).ToList();
return summaryList;

第二个例子

List<CMSSummary> summaryList = db.CMSUpdates
    .Where(i => i.Content.Contains(searchTerm))  // only this line is different
    .AsEnumerable().Select(i => new CMSSummary
    {
        CMSObjectID = i.CMSObjectID,
        Title = i.Title,
        SubTitle = i.PublishDate.ToString("ddd dd MMM"),
        ToolTip = i.Title,
        Summary = i.Summary,
        MainImage = i.MainImage,
        ItemURL = i.URL,
        FullURL = "/mockup/cmspage/" + i.URL,
        HTMLClasses = ""
    }).ToList();
return summaryList;

1 个答案:

答案 0 :(得分:3)

(注意:我没有测试这段代码(需要做太多准备),所以可能会有一些错误)

您有两种选择。

首先是使用the Where extension method接受Expression<Func<CMSUpdate, bool>>作为谓词的事实。因此,您只需创建自己的方法,接受Expression<Func<CMSUpdate, bool>>作为参数,并使用该参数构建查询:

List<CMSSummary> SummaryList(Expression<Func<CMSUpdate, bool>> predicate){
    return db.CMSUpdates.Where(predicate)
    .AsEnumerable().Select(i => new CMSSummary
            {
            CMSObjectID = i.CMSObjectID,
            Title = i.Title,
            SubTitle = i.PublishDate.ToString("ddd dd MMM"),
            ToolTip = i.Title,
            Summary = i.Summary,
            MainImage = i.MainImage,
            ItemURL = i.URL,
            FullURL = "/mockup/cmspage/" + i.URL,
            HTMLClasses = ""
            }).ToList();
}

并使用谓词调用它:

SummaryList(i => i.PublishDate.Year == year)
SummaryList(i => i.Content.Contains(searchTerm))

(您可能需要更改它以传递db作为参数)。

另一种选择是使用Where扩展方法返回IQueryable<CMSUpdate>的事实,并创建一个从IQueryable<CMSUpdate>方法获取Where的方法并应用查询的其余部分:

List<CMSSummary> ToSummaryList(IQueryable<CMSUpdate> query){
    return query.AsEnumerable().Select(i => new CMSSummary
                {
                CMSObjectID = i.CMSObjectID,
                Title = i.Title,
                SubTitle = i.PublishDate.ToString("ddd dd MMM"),
                ToolTip = i.Title,
                Summary = i.Summary,
                MainImage = i.MainImage,
                ItemURL = i.URL,
                FullURL = "/mockup/cmspage/" + i.URL,
                HTMLClasses = ""
                }).ToList();
}

用半查询调用它:

ToSummaryList(db.CMSUpdates.Where(i => i.PublishDate.Year == year))
ToSummaryList(db.CMSUpdates.Where(i => i.Content.Contains(searchTerm)))