contains in linq query

前端 未结 4 406
青春惊慌失措
青春惊慌失措 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-16 02:36

    Try to use this :

    protected Expression> BuildContainsExpression(Expression> valueSelector, IEnumerable 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((accumulate, equal) => Expression.Or(accumulate, equal));
    
                return Expression.Lambda>(body, p);
    }
    

    call the method like this :

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

    This will solve your problem.

提交回复
热议问题