1

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

3
  • That’s.. valid?!? Commented Mar 17, 2020 at 17:42
  • Anyway, I think you might be looking for something like Where(x => (q == null || x.q == q) && ..) ; that is, the guards are moved INSIDE the filter. Otherwise CHAIN filters: f = ..; if (q != null) { f = f.Where(x => x.q == q); } Commented Mar 17, 2020 at 17:44
  • Being optional parameters is itself irrelevant. Commented Mar 17, 2020 at 17:47

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.