动态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());
但是,这给了错误:
But this gives error:
不适用的方法'包含'存在于型的Int32
"No applicable method 'Contains' exists in type 'Int32'"
我怎样才能做到这一点?
How can I achieve this?
有一些扩展库实现包含
为动态
的LINQ或一些其他的方式。
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)));
当然,你也可以只提供了做所有你自己的其中,
扩展方法一次:
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屋!