C#谓词列表传递给Linq Where子句 [英] C# predicate list passed to Linq Where clause

查看:46
本文介绍了C#谓词列表传递给Linq Where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的Linq Where子句,我想用一个谓词列表来填充.

I have a long Linq Where clause that I would like to populate with a predicate list.

List<Expression<Func<Note, bool>>> filters = new List<Expression<Func<Note, bool>>>();

filters.Add(p => p.Title != null && p.Title.ToLower().Contains(searchString));
filters.Add(p => p.Notes != null && p.Notes.ToLower().Contains(searchString));
filters.Add(GlobalSearchUser((List < User > users = new List<User>() { p.user1, p.user2, p.user3, p.user4 }), searchString));

notes = dataAccess.GetList<Note>(pn => pn.ProjectVersionID == projectVersionID, filterExtensions.ToArray())
      .Where(filters.ToArray()).Take(10).ToList();

但是我遇到此错误:

无法从'System.Linq.Expressions.Expression<System.Func<project.Contracts.DTOs.Note,bool>>[]' to 'System.Func<project.Contracts.DTOs.Note,bool>'

.where子句上的错误.拉出.where编译就好了.

Which is an error on the .where clause. Pulling out the .where compiles just fine.

推荐答案

您必须遍历过滤器并在每个过滤器上进行测试.

You have to loop over your filters and run a test on each one.

您可以使用linq这样做,如果任何的过滤器为true,则返回 true :

You can do it with linq like this to return true if any of your filters are true:

.Where(p => { foreach(f in filters) if (f(p) == true) return(true); return(false)}) 

,或者如果您的过滤器所有为true,则返回 true :

or like this to to return true if all of your filters are true:

.Where(p => { foreach(f in filters) if (f(p) == false) return(false); return(true)}) 

这篇关于C#谓词列表传递给Linq Where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆