Reputation: 10021
I'm trying to understand predicate builder
so I can apply it to a web app I'm creating.
Basically I have 4 parameters that come in through a POST request, 'name', 'location', 'age', 'gender', and I have to filter out people from a database table based on these parameters.
problem is, every parameter has the possibility of being 'All' (meaning, if name = 'All', that means don't filter out people by name, if location = 'All' don't filter people by location etc...).
So one way I thought of doing this is to get all people into a list, and have 4 if statements:
if (name != 'All') {
//filter list of people by name string
}
if (location != 'All') {
//filter list of people by location
}
but I don't want to do this, I want to use predicate builder to build the linq expression and only get a list of people who match the parameters, but I don't understand what predicate builder is doing.
This is the site I'm looking at but it doesn't really explain what's going on, and I don't know how to apply it to my situation
Upvotes: 2
Views: 523
Reputation: 35117
Perhaps I'm not understanding the issue but why can't you just do:
query = name == "All" ? query : query.Where(x => x.Name == name);
query = location == "All" ? query : query.Where(x => x.Location == location);
For your particular situation I think what you need to do is:
var query = db.People;
query = name == "All" ? query : query.Where(x => x.Name == name);
query = location == "All" ? query : query.Where(x => x.Location == location);
query = age == "All" ? query : query.Where(x => x.Age == age);
query = weight == "All" ? query : query.Where(x => x.Weight == weight);
var results = query.ToList();
Upvotes: 3
Reputation: 601
If there are only four parameters then I would just use default parameter values and a conditional Linq Where
clause. I included the StartsWith()
, EndsWith()
, and Contains()
to show other possibilities.
Updated to clarify where the database interaction is happening.
public class Example {
private IRepository repos;
//pass in your database context abstract here
public Example(IRepository repos){
this.repos = repos;
}
public IEnumerable<Person> PostMethod(string name = "All", string age = "All",
string height = "All", string weight = "All") {
//reference your database abstract here
return repos.People.Where(x => name == "All" || x.Name == name)
.Where(x => age == "All" || x.Age.Contains(age))
.Where(x => height == "All" || x.Height.StartsWith(height))
.Where(x => weight == "All" || x.Weight.EndsWith(weight));
}
}
Upvotes: 2