Reputation: 7504
I have up to 4 values: string firstName, string lastName, string ssn, DateTime dateOfInjury. The user can enter any one of these or any combination. If they enter more than one, I want to return results using AND. For example, where firstName matches (if that's all they enter), or if firstName AND lastName match if they enter both of them, and so on. What's the best way to do this with LINQ? I'm hoping there's something more elegant that a giant switch statement.
I was planning on building the where clause dynamically, but it doesn't seem like that will work: Building dynamic where clauses in LINQ to EF queries.
Upvotes: 1
Views: 545
Reputation: 110211
Just build up your query. If you have a sequence of Where calls, those are AND'd together.
IQueryable<Customer> query = source.Customers;
if (firstName != null)
{
query = query.Where(c => c.FirstName == firstName);
}
if (lastName != null)
{
query = query.Where(c => c.LastName == lastName);
}
Upvotes: 2