为Any()方法动态构建LINQ过滤器? [英] Dynamically build LINQ filter for the Any() method?
本文介绍了为Any()方法动态构建LINQ过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Any()接收一个Func
如何动态构建过滤器?即:
Any() takes in a Func how can I dynamically build up filters to it? ie:
var filter = () a=> a.Text == "ok";//add the first filter
if (flag)
filter += () a=> a.ID == 5;//add the second filter << obviously this doesn't work.
list.Any(filter);
我还看到了代码,结合了一个表达式>的列表,但我不是得到这个工作,因为我不知道如何转换为Func
I've also seen code out there to combine a list of Expression> , but i'm not getting that to work because I don't know how to convert it toFunc
任何帮助将不胜感激。
推荐答案
您可以通过从当前的其他过滤器调用过滤器,如下所示:
You can compose filters by calling other filters from your current one, like this:
var input = new[] {"quick", "brown", "fox", "jumps"};
Func<string,bool> filter1 = a => a == "quick";
Func<string,bool> filter2 = a => filter1(a) || a.Length == 3;
foreach (var s in input.Where(filter2)) {
Console.WriteLine(s);
}
打印
quick
fox
您可以对任何基于谓词的方法使用相同的方法LINQ的功能,包括任何
:
You can use the same approach for any predicate-based functions of LINQ, including Any
:
if (input.Any(filter2)) {
...
}
这篇关于为Any()方法动态构建LINQ过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文