构建查询以根据OR条件进行过滤

本文关键字:条件 过滤 OR 查询 构建 | 更新日期: 2023-09-27 18:18:38

我试图建立一个查询,我根据主题过滤新闻。每条新闻都可以有几个主题。当我进行筛选时,我想获得包含我所筛选的任何主题的每个新闻项目,但我得到的是包含我所选择的所有主题的新闻项目。

我已经尝试了很多不同的解决方案,这是我现在有的。什么好主意吗?

IQueryable<News> news = context.News;
if (themes.Any())
{
  foreach (var t in themes)
  {
    news = news.Where(n => n.Post.Themes.Count > 0).Where(n => n.Post.Themes.Select(th => th.Id).Contains(t.Id)); 
  }
}
return news.ToList();

构建查询以根据OR条件进行过滤

根据您的代码,您可以将主题id放入数组并将其传递给Contains扩展

IQueryable<News> news = context.News;
var themesIds = themes.Select(t=>t.Id).ToArray();
news = news.Where(n =>  n.Post.Themes.Any(t=>themesIds.Contains(t.Id))); 
return news.ToList();

尝试将themes声明为HasSet并使用下一个查询:

news.Where(n => n.Post.Themes.Any(t => themes.Contains(t)))

UPDATE:这里不需要HashSet。数组已经足够好了。感谢@KingKing和@Dennis

您可以为您的News类编写一个扩展方法。

public static class NewsExtensions {
public static List<News> GetNewsByTheme(this List<News> news, List<Theme> themes) {
    List<News> result = new List<News>();
    foreach(var theme in themes) {
        foreach(var newsItem in news) {
            ...some logic here
            result.Add(newsItem);
        }
    }
    return result;
}

然后在代码中调用:

List<News> newsContainingThemes = news.GetNewsByTheme(themes);