user1086355
user1086355

Reputation: 1343

contains in linq query

Hi i am using entity framework and LinQ. I have a table objects called users . i have a list called userids. i have to find all users where ids contains in the string. I have to do following operations ...

select * from users where userid in (userids);

I tried to solve this like this

var u = context.users.Where(o=> usersid.Contains(o=> o.userid)).Select(o=> o);

but it gives compilation error. how to solve this ?

Upvotes: 1

Views: 887

Answers (4)

Brian Cauthon
Brian Cauthon

Reputation: 5534

Assuming userids is an IEnumerable of the same type as User.userid, try changing your LINQ query to:

var u = context.users.Where(o=> userids.Contains(o.userid)); 

Upvotes: 0

Dewasish Mitruka
Dewasish Mitruka

Reputation: 2896

Try to use this :

protected 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();

            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);
}

call the method like this :

var u = context.users.Where(BuildContainsExpression<user, Int32>(e => e.Userid, userids)).ToList();

This will solve your problem.

Upvotes: 0

msarchet
msarchet

Reputation: 15242

var u = context.users,Where(o=> usersid.contains(o=> o.userid)),select(o=> o);

Assuming that this is the code you are using

var u = context.users.Where(o=> usersid.Contains(o => o.userid)).Select(o => o);

make sure that you are using . instead of , and that you have the correct case on your Methods.

Upvotes: 0

Chris E
Chris E

Reputation: 983

Put periods instead of commas.

Try

var u = context.users.Where(o=> usersid.Contains(o=> o.userid)).Select(o=> o);

Upvotes: 1

Related Questions