动态构建Any()方法的LINQ过滤器?

时间:2013-04-26 02:20:59

标签: linq dynamic filter

Any()接受一个Func 如何动态构建过滤器?即:

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

我还看到了代码组合表达式&gt; ,但我不能让它工作,因为我不知道如何将其转换为Func

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:3)

您可以通过调用当前过滤器中的其他过滤器来组合过滤器,如下所示:

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

Demo on ideone

您可以对LINQ的任何基于谓词的函数使用相同的方法,包括Any

if (input.Any(filter2)) {
    ...
}

答案 1 :(得分:0)

您可以像Any这样添加多个过滤器。

list.Any(a=>a.Text == "ok" && a.ID == 5);

答案 2 :(得分:0)

您可以创建IEnumerable<Func<T,bool>>然后查询它,例如

Func<int,bool> isGreaterThanEight = x => x > 8;
Func<int,bool> isEven = x => x % 2 == 0;
Func<int,bool> hasFactorFive = x => x % 5 == 0;

IEnumerable<Func<int,bool>> rules = new List<Func<int,bool>>() 
    { isGreaterThanEight, isEven, hasFactorFive };

var nums = Enumerable.Range(1,10);

var actual = nums.Where( x => rules.Any( r => r(x) ) );

Assert.That( actual, Is.EqualTo( new[]{2,4,5,6,8,9,10} ) );