【发布时间】:2014-09-17 10:36:02
【问题描述】:
好吧,我不确定问题的标题是否足够清楚,但我想不出一句话更简单的解释。
我正在为 ASP.NET Web 应用程序制作搜索页面。我想允许用户使用不同的过滤器进行搜索。
我想出了一种方法,可以根据用户选择的类别类型过滤出版物(这些是用户将检索的实体)。
List<Publication> publications =
(from p in GetPublications()
where categories.Contains((int)p.CategoryId)
select p).ToList();
上面的linq查询等价于下面的sql之一:
select * from Publication p where p.CategoryId in (@chosenCategoryIds)
一切都很完美,但问题是我想让用户从更多过滤器中进行选择,例如,不仅是类别,还有用户、标签、标题等。
所以,如果我想要这个,我应该做很多条件语句来检查用户是否提供了给定的过滤器,比如:
if (categories != null)
{
var publications = (from p in GetPublications()
where categories.Contains((int)p.CategoryId)
select p).ToList();
if (users != null)
{
publications = (from p in publications
where users.Contains((int)p.UserId)
select p).ToList();
}
}
else
{
// Handle other situations..
}
所以,事实证明,对于不同的过滤器,我基本上都在做同样的事情。我的问题是,是否有人知道或能想出更好的方法来实现这一目标?如果没有,我们来看看下面的方法:
public List<InterpretumDAL.Publication> FilterPublications(List<InterpretumDAL.Publication> oldList, int[] values)
{
List<InterpretumDAL.Publication> newList =
(from p in oldList
where values.Contains((int)p.CategoryId)
select p).ToList();
return newList;
}
我尝试使用上述方法实现的是通过给定值数组过滤给定列表。问题是我不知道如何告诉方法要比较哪个属性,所以我可以这样称呼它:
newList = FilterPublications(publications, categories, CATEGORY_PROPERTY_OF_PUBLICATION);
newList = FilterPublications(publications, users, USER_PROPERTY_OF_PUBLICATION);
newList = FilterPublications(publications, tags, TAG_PROPERTY_OF_PUBLICATION);
编辑: 根据 LiquidPony 的回答,我是这样做的:
var publications = (from p in GetPublications()
where (
(categories == null || categories.Length == 0 || (p.CategoryId.HasValue && categories.Contains((int)p.CategoryId)))
&& (users == null || users.Length == 0 || users.Contains(p.UserId))
&& (tags == null || tags.Length == 0 || tags.Contains(p.TagId))
)
select p).ToList();
【问题讨论】:
标签: c# algorithm linq entity-framework search