PPKR
PPKR

Reputation: 41

Combine multiple where conditions having optional parameters in C# linq?

I am searching for a LINQ query where I have 3 parameters and two are optional parameters for this I wrote if-else conditions like below

if (id != null) { where condition} 
else if (name!= null) { where condition } 
else if (category != null) { where condition } 
else if (id != null && name != null) { where condition } 
else if (id != null && category != null) { where condition } 
else if (name != null && category != null) {where condition} 
else if (id != null && name != null && category != null ) { where condition } 

I don't want to write more if-else conditions if there is another optional parameter added

Note. Id is not a primary key

Upvotes: 1

Views: 1105

Answers (3)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 88996

The optimal pattern for this in EF is to add the Where conditions only conditionally. EG

IQueryable<SomeType> qry = ...;
if (id != null)
{
  qry = qry.Where(x => x.Id == id);
}
if (name != null)
{
  qry = qry.Where(x => x.Name == name);
}
if (category != null)
{
  qry = qry.Where(x => x.Category == category);
}
var results = qry.ToList();

That way you don't clutter up the expression with lots of predicates that don't do anything, but which can mess up the query execution.

Upvotes: 2

Alex - Tin Le
Alex - Tin Le

Reputation: 2000

What I always do is below. Easy to read and remember.

myList
    .Where(x => id == null || x.Id == id)
    .Where(x => name == null || x.Name == name)
    .Where(x => category == null || x.Category == category);

Upvotes: 1

Shervin Ivari
Shervin Ivari

Reputation: 2501

You can write it like this

id == null ? true : {id condition} &&
name == null ? true : {name condition} &&
category == null ? true: {category } and other conditions

Or

id == null || {id condition} &&
id == null || {id condition} &&

returning true will make the statement true if its value equals null. its clean, Easy to understand and develop.

I hope it helps.

Upvotes: 0

Related Questions