contains in linq query

前端 未结 4 399
青春惊慌失措
青春惊慌失措 2021-01-16 01:59

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 hav

相关标签:
4条回答
  • 2021-01-16 02:20
    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.

    0 讨论(0)
  • 2021-01-16 02:35

    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)); 
    
    0 讨论(0)
  • 2021-01-16 02:36

    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.

    0 讨论(0)
  • 2021-01-16 02:38

    Put periods instead of commas.

    Try

    var u = context.users.Where(o=> usersid.Contains(o=> o.userid)).Select(o=> o);
    
    0 讨论(0)
提交回复
热议问题