Meena
Meena

Reputation: 715

Apply filters only if parameters has values in linq

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.

Upvotes: 2

Views: 1349

Answers (2)

Sadik
Sadik

Reputation: 1

You can define a function and filter by this function using LINQ operation. C# supports functional programming in linq operations.

Here below I defined a function(filterAccounts) that returns boolean if satisfies the requirements.

After that I sent this function as a parameter to Linq Where method. Where method call's filterAccounts method for each element and if returns true, than yields it and finally returns all elements that returns true.

I hope it helps.

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

Upvotes: 0

fubo
fubo

Reputation: 45967

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!

Upvotes: 2

Related Questions