views:

535

answers:

4

I'm currently building a detailed search and I am trying to figure out how to compose my Linq query to my Entity.

basically I have users that can select 1* items in a list control. the part I can't wrap my head around is the following:

how can I dynamically build a Where AND( field is equal to this OR field is equal to this OR...) clause where the number of items is variant.

database Domain Field sample content : '26, 21, 22, 100, 164, 130'

Example: (The idea is to be able to generate this depending on the number of items selected)

Offre.Where(o=> o.Domain.Contains("26") || o.Domain.Contains("100") )

Offre.Where(o=> o.Domain.Contains("26") )

Offre.Where(o=> o.Domain.Contains("26") || o.Domain.Contains("100") || o.Domain.Contains("22") )

then I can easily have the resulting query as an IQueryable and add on to this object to build my query.

can someone point me inthe right direction for my AND ( OR .. OR ) clause ?

+2  A: 

To work around this restriction, you can manually construct an expression (Source)

C#

static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(

    Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)

{

    if (null == valueSelector) { throw new ArgumentNullException("valueSelector"); }

    if (null == values) { throw new ArgumentNullException("values"); }

    ParameterExpression p = valueSelector.Parameters.Single();

    // p => valueSelector(p) == values[0] || valueSelector(p) == ...

    if (!values.Any())

    {

        return e => false;

    }

    var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));

    var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));

    return Expression.Lambda<Func<TElement, bool>>(body, p);

}

Using this utility method,

var query2 = context.Entities.Where(BuildContainsExpression<Entity, int>(e => e.ID, ids));

VB.Net

Public Shared Function BuildContainsExpression(Of TElement, TValue)( _
ByVal valueSelector As Expression(Of Func(Of TElement, TValue)), _
ByVal values As IEnumerable(Of TValue) _
   ) As Expression(Of Func(Of TElement, Boolean))

    ' validate arguments
    If IsNothing(valueSelector) Then Throw New ArgumentNullException("valueSelector")
    If IsNothing(values) Then Throw New ArgumentNullException("values")

    Dim p As ParameterExpression = valueSelector.Parameters.Single()
    If Not values.Any Then
        Return _
            Function(e) False
    End If

    Dim equals = values.Select( _
        Function(v) _
            Expression.Equal(valueSelector.Body, Expression.Constant(v, GetType(TValue))) _
    )

    Dim body = equals.Aggregate( _
        Function(accumulate, equal) _
            Expression.Or(accumulate, equal) _
    )

    Return Expression.Lambda(Of Func(Of TElement, Boolean))(body, p)
End Function

Using this utility method

   Dim query = m_data. Offer

   If (selectedSectors.Count > 0) Then
        query = query.Where(BuildContainsExpression(Function(o As Offer) o.Value, selectedSectors))
   End If
Alexandre Brisebois
A: 

If your Offre has some kind of unique Id associated with it, you could try the following:

List<int> queryCriteria = new List<int>;

//Fill your query criteria here

//Instead of o.Domain.Id you can use whatever ID you have.
var resultSet = Offre.Where(o => queryCriteria.Contains(o.Domain.Id));
Correl
This is good when you are doing Linq to Objects, but I want my query to execute completely on the SQL Server.
Alexandre Brisebois
Sorry, my boss keeps calling objects entities, so I keep mixing those two up.
Correl
A: 

Can't upvote Alexandre solution, but definitely desserves it. Thanks, you saved my life :)

Bishop