Dynamically create a LINQ filter for the Any () method?

Anyone () accepts in Func how can I dynamically create filters? i.e:

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 also saw code for combining an Expression> list, but I do not get this to work, because I do not know how to convert it to Func

Any help would be greatly appreciated.

+4
source share
3 answers

You can create filters by calling other filters from your current one, for example:

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

Will print

 quick fox 

Demo on ideon .

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

 if (input.Any(filter2)) { ... } 
+3
source

You can add multiple filters to Any like this.

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

You can create an IEnumerable<Func<T,bool>> , then query it for example.

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

All Articles