我很难为这篇文章找到合适的标题。但我有以下内容:
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));
所以一些解释:article
有一个 Title
和一个 CreateDate
,通过它们进行过滤很容易。但是 article
也有与之关联的 categories
。因此,文章
具有类别
类型的数组
属性。类型 Category
有一个名为 CategoryId
的属性,类型为 int
。
所以在我的注释掉的代码中,我试图选择
一个article
,它有一个与之关联的类别
,谁的 CategoryId
等于..说 4
。
但我发现很难用我的 C# 语法表达这一点。我也是 C# 的新手,所以这也没有帮助。
最佳答案
你不需要写两个 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));
对于多个类别,假设您的类别 ID 在 int[]
中或 List<int>
名为 MyCatIDsList
.您可以将上述查询中的类别子句更改为:
a.Categories.Any(c => MyCatIDsList.Contains(c.CategoryID))
关于c# - IQueryable where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28625127/