LINQ, Large filter on request

I am creating an application section that revolves around pulling transaction information from a database. Due to the nature of the data in the table, there are many columns that I want to filter. I have a filter selection field with 15 fields that I want to create a where clause for the LINQ statement. The interesting part comes up when I want certain fields to be null. For example, I want to be able to filter any or all of them:

  • Transaction type
  • Response code
  • Transaction Amount
  • Much more

I can create a predicate that looks like

Func<Transaction, bool> pred = t => t.ResponseCode == ResponseCode && t.TransactionType == TransactionType && t.TransactionAmount > 100.00;

But in order to choose which fields to include in the predicate, I combine the predicates together:

Func<Transaction, bool> pred = t => true;
if(ResponseCode != null)
   pred.AndAlso(t => t.ResponseCode == ResponseCode);
// Rinse and repeat

And then pass this predicate to the where clause of the LINQ statement.

, , . ?

UPDATE: . LINQ to SQL, LINQ . Expression?

+3
2
  • SQL... WHERE - AND.
  • linq... WHERE, . Linq , .

:

IQueryable<Transaction> query = db.Transactions;

if (filterByTransactionType)
{
  query = query.Where(t => t.TransactionType == theTransactionType);
}
if (filterByResponseCode)
{
  query = query.Where(t => t.ResponseCode == theResponseCode);
}
if (filterByAmount)
{
  query = query.Where(t => t.TransactionAmount > theAmount);
}

:

List<Expression<Func<Transaction, bool>>> filters = GetFilterExpressions();

IQueryable<Transaction> query = db.Transactions;
filters.ForEach(f => query = query.Where(f));
+8

-, Expression<Func<Transaction, bool>> LINQ-to-SQL ( , , , LINQ).

-, Expression<Func<Transaction, bool>> System.Linq.Expression.

LINQ per se . : , from p in db.People where p.Age > 50 select p.Name db.People.Where(p => p.Age > 50). : db.People.Where(myFilter), myFilter = new Expression<Func<Person, bool>>(p => p.Age > 50). myFilter , , -.

0

Source: https://habr.com/ru/post/1702429/


All Articles