Dynamically changing number of conditions in a where expression using LINQ

I am working on my first project using LINQ (in mvc), so maybe something is very simple that I missed. However, the day of searching and experimenting showed nothing that works, hence the message.

I am trying to write a LINQ (Linq to SQL) query that will contain several conditions in a where statement, separated by OR or AND. We do not know how many conditions will be in the request before fulfillment. This is to manage the search filter, where the user can select several criteria for filtering.

select * from table
where table.col = 1 
    OR table.col = 2
    OR table.col = 7
    .... 'number of other conditions

Before I just build the SQL query as a string, by going through all the conditions. However, there seems to be a good way to do this in LINQ. I tried looking for expression trees, but at the moment they seem a little steep to me. Another idea was to execute a lambda function inside the where statement, for example:

For Each value In values
    matchingRows = matchingRows.Where(Function(row) row.col = value)

However, this only works for conditions I. How to make ORs?

+3
source share
3 answers

I would use PredicateBuilder for this. This makes WHERE dynamic clauses very light.

+2
source

AND - Where . OR . SQL, , - LINQ-to-SQL, , , Expression - ( - #, , , VB, VB , ... , , # , VB).

, EF 3.5SP1 (- Expression.Invoke), , 4.0.

+1

- ( VB):

Expression(Of Func(Of Something, Boolean)) filter = Nothing
ParameterExpression rowParam = Expression.Parameter("row", CType(Something))

For Each value In values
    filterPart = Expression.Equal( _
        Expression.Property(rowParam, "col"), _
        Expression.Constant(value)))
    If filter Is Nothing Then
        filter = filterPart 
    Else
        filter = Expression.OrElse(filter, filterPart)
    End If
Next

If newPredicate IsNot Nothing Then
    matchingRows = matchingRows.Where( _
        Expression.Lambda(Of Func(Of SomeType, Boolean))(filter, rowParam))
End If

, , VB : -)

PredicateBuilder , , And Or s.

0
source

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


All Articles