c# – IQueryable where子句
发布时间:2020-12-16 00:25:05 所属栏目:百科 来源:网络整理
导读:我很难找到这篇文章的合适标题.但我有以下几点: IArticleRepository articleRepo = unitOfWork.ArticleRepository;ListArticle articles = new ListArticle( articleRepo.GetAll() .Where(a = a.Title == searchTerm) //.Where(a = a.Categories.Contains(C
我很难找到这篇文章的合适标题.但我有以下几点:
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)); 所以有一些解释:一篇文章除其他外,还有一个Title和一个CreateDate,过滤这些很容易.但是文章也有与之相关的类别.所以文章有一个Category类型的数组属性. Type Category有一个名为CategoryId的属性,类型为int. 所以在我注释掉的代码中,我试图选择一篇文章,它有一个与之相关的类别,其CategoryId等于…说4. 但我发现在我的C#语法中表达这一点非常困难.我也是C#的新手,所以这也没有帮助. 解决方法
你不需要写两个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)); 对于多个类别,假设您在Int []或List< int>中有CategoryID.名为MyCatIDsList.他们可以将上面查询中的categories子句更改为: a.Categories.Any(c => MyCatIDsList.Contains(c.CategoryID)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |