动态 Linq 查询包含列表 [英] Dynamic Linq query Contains List
问题描述
我使用动态 Linq 进行通用搜索.我有 ID 列表:
I am using dynamic Linq for generic search. I have list of Ids:
List<int> idList = new List<int> { 1, 5, 6};
在普通的 Linq 中,我会这样写:
In plain Linq, I would write:
q = q.Where(a => idList.Contains(a.MyId));
但现在我必须使用System.Linq.Dynamic
,因为我事先不知道列的名称.
But now I have to use System.Linq.Dynamic
because I don't know in advance name of the column.
string someId = "CustomId";
q = q.Where("@0"+ ".Contains(" + someId + ")", idList.ToArray());
但这会导致错误:
类型 'Int32' 中不存在适用的方法 'Contains'"
"No applicable method 'Contains' exists in type 'Int32'"
我怎样才能做到这一点?
How can I achieve this?
是否有一些扩展库为 dynamic
Linq 或其他方式实现了 Contains
.
Is there some extension library that implements Contains
for dynamic
Linq or some other way.
推荐答案
你可以写这样的东西来动态构建你的查询函数:
You could write something like this that builds your query function dynamically:
public static Func<ObjT, bool> PropertyCheck<ObjT, PropT>(string propertyName, Expression<Func<PropT, bool>> predicate)
{
var paramExpr = Expression.Parameter(typeof(ObjT));
var propExpr = Expression.Property(paramExpr, propertyName);
return Expression.Lambda<Func<ObjT, bool>>(Expression.Invoke(predicate, propExpr), paramExpr).Compile();
}
然后,它可以像这样使用:
Then, it could be used like this:
foos.Where(PropertyCheck<Foo, int>("MyId", x => idList.Contains(x)));
当然,您也可以提供自己的 Where
扩展方法来一次性完成所有操作:
Of course, you could also just provide your own Where
extension method that does all that at once:
public static IEnumerable<T> Where<T, PropT>(this IEnumerable<T> self, string propertyName, Expression<Func<PropT, bool>> predicate)
{
var paramExpr = Expression.Parameter(typeof(T));
var propExpr = Expression.Property(paramExpr, propertyName);
return self.Where<T>(Expression.Lambda<Func<T, bool>>(Expression.Invoke(predicate, propExpr), paramExpr).Compile());
}
foos.Where<Foo, int>("MyId", x => idList.Contains(x));
这篇关于动态 Linq 查询包含列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!