IQueryable where子句

3 c# linq iqueryable

我很难找到这篇文章的合适标题.但我有以下几点:

IArticleRepository articleRepo = unitOfWork.ArticleRepository;
List<Article> articles = new List<Article>(
                         articleRepo.GetAll()
                         .Where(a => a.Title == searchTerm)
                         //.Where(a => a.Categories.Contains(Category.))
                         .OrderByDescending(a => a.CreatedDate));  
Run Code Online (Sandbox Code Playgroud)

所以有一些解释:An article除了其他之外还有a Title和a CreateDate,并且通过它们进行过滤很容易.但是article也有categories它与之相关.所以article有一个array类型的属性Category.Type Category有一个名为CategoryIdtype 的属性int.

因此,在我的代码中,它被注释掉了,我正在尝试一个与之相关的select一个article,它等于......说.categoryCategoryId4

但我发现在我的C#语法中表达这一点非常困难.我也是C#的新手,所以这也没有帮助.

dot*_*NET 8

你不需要写两个Where条款; 只是为你的第一个添加另一个条件Where.第二个条件应该使用Any函数来搜索您正在寻找的类别.

IArticleRepository articleRepo = unitOfWork.ArticleRepository;
List<Article> articles = new List<Article>(
                     articleRepo.GetAll()
                     .Where(a => a.Title == searchTerm &&
                                 a.Categories.Any(c => c.CategoryID == 4))
                     .OrderByDescending(a => a.CreatedDate));  
Run Code Online (Sandbox Code Playgroud)

对于多个类别,假设您有一个int[]List<int>命名的CategoryID MyCatIDsList.他们可以将上面查询中的categories子句更改为:

              a.Categories.Any(c => MyCatIDsList.Contains(c.CategoryID))
Run Code Online (Sandbox Code Playgroud)