0

I am working with OData and .NET DataServiceQuery class. I have an instance where I want to query OData service for multiple entities based on ID (ID in 1,2,3)). However, OData needs this as a ID = 1 or ID = 2 or ID = 3 format, which is fine. But on the client side, I don't know how many IDs I will need ahead of time, so I need to be able to translate the following:

List ids = .... query.Where(x => ids.Contains(x.ID)

I am already familiar with creating my own IQueryable and I'm doing that and translating other portions of the LINQ expression. I'm just not sure how to translate the Contains lambda into the OR lambda, evaluating the incoming list to generate the conditions.

Rich
  • 2,076
  • 1
  • 15
  • 16

2 Answers2

3

You should create a new expression in this fashion. Something like this:

public Expression GetOrExpression( MethodCallExpression containsExpression )
{
    var list = (IEnumerable)((ConstantExpression)containsExpression.Object).Value;
    var p = containsExpression.Arguments[0];

    Expression expression;

    foreach(var item in list)
    {
        var equal = Expression.Equal(p, item);
        if(expression == null)
            expression = equal;
        else
            expression = Expression.OrElse(expression, equal);
    }
    return expression;
}

Hope it helps.

Ivo
  • 8,172
  • 5
  • 27
  • 42
  • This helped. The portion to evaluate the list itself didn't work as expected, but I found the following to figure that out: http://stackoverflow.com/questions/2616638/access-the-value-of-a-member-expression – Rich Jan 03 '13 at 18:23
2

You can leverage Dynamic Linq and query with a run time generated string. Basically that extension methods suite allow you to code the linq static statement as a string that is compiled at execution time.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115