tags:

views:

58

answers:

2

I am using the System.Linq.Dynamic library to power a GUI base query engine however I can't seem to find support for the equivalent of the Sql IN operator. Has anyone used this?

I have searched and found a couple of possible duplicates here however none have been exactly what I am asking (or have been solved).

Clarification:

I am using the dynamic query API to build queries in Linq, e.g:

var customers = dbDataContext
                 .Clients
                 .Where("Lastname = @0", "Smith");

Which works fine, the one operator I am struggling with is an equivalent to the Sql IN operator. I would like to do this:

var customers = dbDataContext
                 .Clients
                 .Where("ProductIDsPurchased IN (1,6,8,90)");

However I am not sure how to write this using dynamic queries (the above does not work).

+1  A: 

Hi,

Probably this Stackoverflow thread can help you...

Excerpt from the thread:

you could implement your own WhereIn method :

public static IQueryable<TEntity> WhereIn<TEntity, TValue>
 (
     this ObjectQuery<TEntity> query, 
     Expression<Func<TEntity, TValue>> selector, 
     IEnumerable<TValue> collection
 )
{
    if (selector == null) throw new ArgumentNullException("selector");
    if (collection == null) throw new ArgumentNullException("collection");
    ParameterExpression p = selector.Parameters.Single();

    if (!collection.Any()) return query;

    IEnumerable<Expression> equals = collection.Select(value => 
      (Expression)Expression.Equal(selector.Body, 
       Expression.Constant(value, typeof(TValue))));

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

    return query.Where(Expression.Lambda<Func<TEntity, bool>>(body, p));
}

Usage:

public static void Main(string[] args)
{
    using (Context context = new Context())
    {
        //args contains arg.Arg
        var arguments = context.Arguments.WhereIn(arg => arg.Arg, args);   
    }
}

In your case:

var customers = dbDataContext
             .Clients
             .WhereIn(c=> c.LastName, new List<string>{"Smith","Wesson"});

HTH

Stephane
Thanks for the extensive answer and examples - I'll give this a go
Macros
This won't work in the way I am after as the fieldname also needs to be dynamic
Macros
Check out David Buchanan's approach to this problem. He uses reflection to do exactly this.http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/5edb3dd0-c778-47e2-b89d-a9c90a0bd1bc/
Stephane
A: 

When I use the Contains method of a collection, I find that LINQ-to-SQL generates an "IN" expression for me.

BlueMonkMN
Using Contains is fine in a normal query but it doesn't seem to have a mapping to a dynamic query
Macros