首页 新闻 会员 周边 捐助

如何动态拼接出.Where(c => List.Contains(c.Id));

0
悬赏园豆:10 [已解决问题] 解决于 2018-12-12 14:47

实现了一个==的拼接 不知道怎么实现Contains的拼接:

public static IQueryable<T> WhereEqual<T>(this IQueryable<T> q, string fieldName, string fieldValue)
    {
        Type t = typeof(T);
        ParameterExpression param = Expression.Parameter(t, "c");
        Expression left = Expression.Property(param, t.GetProperty(fieldName));
        Expression right = Expression.Constant(fieldValue);
        //Expression.
        Expression filter = Expression.Equal(left, right); 
        Expression pred = Expression.Lambda(filter, param);
        Expression expr = Expression.Call(typeof(Queryable), "Where", new Type[] { t }, Expression.Constant(q), pred);
        return q.Provider.CreateQuery<T>(expr);

    }
_York的主页 _York | 初学一级 | 园豆:38
提问于:2018-12-12 11:33
< >
分享
最佳答案
1

参考 How do I create an expression tree to represent 'String.Contains(“term”)' in C#?

static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue)
{
    var parameterExp = Expression.Parameter(typeof(T), "type");
    var propertyExp = Expression.Property(parameterExp, propertyName);
    MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    var someValue = Expression.Constant(propertyValue, typeof(string));
    var containsMethodExp = Expression.Call(propertyExp, method, someValue);

    return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
}
收获园豆:10
dudu | 高人七级 |园豆:30734 | 2018-12-12 11:57

感谢 我试试能不能再EF中使用

_York | 园豆:38 (初学一级) | 2018-12-12 12:00
其他回答(1)
0

public Expression<Func<TEntity, bool>> ContainsPredicate<TEntity, T>(T[] arr, string fieldname) where TEntity : class {
ParameterExpression entity = Expression.Parameter(typeof(TEntity), "entity");
MemberExpression member = Expression.Property(entity, fieldname);

var containsMethods = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.Name == "Contains");
MethodInfo method = null;
foreach (var m in containsMethods) {
if (m.GetParameters().Count() == 2) {
method = m;
break;
}
}
method = method.MakeGenericMethod(member.Type);
var exprContains = Expression.Call(method, new Expression[] { Expression.Constant(arr), member });
return Expression.Lambda<Func<TEntity, bool>>(exprContains, entity);
}

_York | 园豆:38 (初学一级) | 2018-12-12 14:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册