Dynamically build LINQ filter for the Any() method?

dynamic, filter, linq

Solution

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

This prints

quick
fox

Demo on ideone.

You can use the same approach for any predicate-based functions of LINQ, including `Any`:

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

Problem

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); ``` 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 Any help would be greatly appreciated.

Original source