It’s already a long time ago I posted something new but now I have something interesting to share.
I had the problem some time ago that I was using LINQ in an application and I needed to create a custom filter on a list.
The problem I discovered with the creation of the filter was that every combination of filter values can be possible.
There are 2 ways of dealing with this problem.
You can catch all the possible combinations or you can make use of predicates.
What are predicates?
Predicates is a mechanism where you can put multiple where clauses in an array an attach that array to a LINQ query.
The advantage of the predicates mechanism is that you can add new where clauses at different places.
So it is possible to check if a field is empty and if not add the where clause to the array.
At the end when all the checks (separate checks on the fields) are done you can create your LINQ query and attach the predicates object.
Here is a code example.
bool predicatePresent = false; var predicate = PredicateBuilder.True<person>(); if (!string.IsNullOrEmpty(firstname)) { predicate = predicate.And(p => p.FirstName.Contains(firstname)); predicatePresent = true; } if (!string.IsNullOrEmpty(lastname)) { predicate = predicate.And(p => p.LastName.Contains(lastname)); predicatePresent = true; } List<person> persons = new List<person>(); if (predicatePresent) { //execute query with filter predicates var results = (from p in MyContext.Person select p).Where(predicate).OrderByDescending(p => p.LastName); persons = results.ToList(); }