c# - IQueryable where 子句

标签 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));  

所以一些解释: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/

相关文章:

c# - LINQ:在 1 个 IQueryable 中返回 2 个 SELECT 进行分页?与存储库模式保持一致并且不更改返回类型

c# - 如何在 LINQ to Entities 查询中实现查询拦截? (C#)

c# - 将鼠标点击发送到另一个应用程序的 X Y 坐标

c# - 在 C# 中创建新 List<string> 的这三种方法有什么区别?

c# - 这两个 LINQtoSQL 语句有什么区别?

Linq 查询递归

c# - LINQ:根据最新时间通过选定的 ID 获取唯一行

javascript - 光 slider 数据拇指图像路径未使用 Eval() 从数据库绑定(bind)

c# - ReadKey while key is not pressed 做某事

c# - LINQ 中的 .Take 方法是否有通配符?