Home > Software engineering >  Apply filters only if parameters has values in linq
Apply filters only if parameters has values in linq

Time:02-04

Iam using LINQ to retrieve records from the database. Everything is working fine, except I need to apply the different filters in a single query. If the parameters are not Null and greater than zero then apply filters. Otherwise, if they are Null or zero, then don't apply the filters. Below is the example:

bankId(int) and accountNumber(string) are my two parameters.
if bankId > 0 then get the records matching the bankId, if accountnumber is passed then get the records matching the accountnumber.
If both are passed pull all the records matching with bankid and accountnumber.
If both are not passed then return all records without applying filter.

Currently I am able to achieve it like this, Without applying any filter I am fetching all records and then if bankId is passed applying filter on the above result and if accountnumber is passed again applying filter on the above result.

But the issue here is this approach is leading to multiple if conditions which I don't want.

Is there any best and simple way to apply these filters in single query and get the result?

Please suggest, Thanks in advance.

CodePudding user response:

build your statement this way

var items = context.accounts.AsQueryable();
if (bankId > 0)
{
    items = items.Where(x => x.bankId == bankId);
}
if (!string.IsNullOrEmpty(accountnumber))
{
    items = items.Where(x => x.accountnumber == accountnumber);
}
var result = items.ToList(); // query db / materialize here!

CodePudding user response:

You can send a function to where condition and filter it as below.

List items = getItemsAslist();
    
    Func<item, bool> filterAccounts = (i) => 
        {
            return (bankId > 0 ? i.bankId == bankId : true) 
                   && (!string.IsNullOrEmpty(accountnumber) ? accountNumber == i.accountNumber : true)
        };
    
    items = items.Where(filterAccounts);
  •  Tags:  
  • Related