我每次都用稍微不同的 WHERE 部分重复以下 linq 代码。
我想遵循 DRY 原则,只指定一次视图模型。有没有办法重用相同的查询并动态指定 WHERE 条件?
我在这里查看了 SO 并遇到了一些类似的问题,但我找不到对我有意义的答案。我错过了一些明显的东西吗?
第一个例子
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;