How do you write a dynamic Linq query for the following simple search criteria?
1) StudentNumber
2) LastName
3) LastName and FirstName
//if (!String.IsNullOrEmpty(StudentNumber))
var results = (from s in Students
where s.StudentNumber == 1001
select s
);
//else if (!String.IsNullOrEmpty(LastName) & (String.IsNullOrEmpty(FirstName))
var results = (from s in Students
where s.LastName == "Tucker"
select s
);
//else if (!String.IsNullOrEmpty(LastName) & (!String.IsNullOrEmpty(FirstName))
var results = (from s in Students
where s.LastName == "Tucker" && s.FirstName == "Ron"
select s
);
You need to declare your
resultsvariable outside of any individual query. This will allow you append different filters based upon your varying criteria, and append as many filters as you need. An example:If dealing with Linq-to-Entities or -Sql, type the initial query with
Students.AsQueryable();so that the filtering happens at the database rather than inside the application.If you want to build the entire
wherebefore the first step of the query, it’s the same logic. You are conditionally building the predicate, so you will have some sort of if/else involved. However, to build the entire predicate first, you could build against aFunc<Student, bool>for Linq to Objects.You’ll notice it’s the exact same if/else structure. You could collapse that down into a complicated conditional expression
But I find that pretty well difficult to follow, certainly as compared to the longer if/else. This predicate is also bigger than the one we build via the if/else, because this one contains all the logic, it’s not just the logic we conditionally added.