c# - c#为列表包含构建通用表达式树
问题描述
您好我想创建一个通用表达式树,它返回一个包含结果的列表。
public static class Extension{
public static List<T> WhereIn<T, T1>(IQueryable<T> query, IEnumerable<T1> keys, Expression<Func<T, T1>> param)
{
}
}
问题是我还想创建这样的东西:
var result = Extension.WhereIn(customers.AsQueryable(), stringList, c => c.Number.ToString());
到目前为止,这适用于静态属性名称:
public static Expression<Func<T, bool>> FilterByCode<T, T1>(List<T1> codes, string propName)
{
var methodInfo = typeof(List<T1>).GetMethod("Contains",
new Type[] { typeof(T1) });
var list = Expression.Constant(codes);
var param = Expression.Parameter(typeof(T), "j");
var value = Expression.Property(param, propName);
var body = Expression.Call(list, methodInfo, value);
// j => codes.Contains(j.Code)
return Expression.Lambda<Func<T, bool>>(body, param);
}
解决方案
感谢Marc Gravell,我得到了解决方案:
public List<T> WhereIn<T, TValue>(IQueryable<T> source, IEnumerable<TValue> keys, Expression<Func<T, TValue>> selector)
{
MethodInfo method = null;
foreach (MethodInfo tmp in typeof(Enumerable).GetMethods(
BindingFlags.Public | BindingFlags.Static))
{
if (tmp.Name == "Contains" && tmp.IsGenericMethodDefinition
&& tmp.GetParameters().Length == 2)
{
method = tmp.MakeGenericMethod(typeof(TValue));
break;
}
}
if (method == null) throw new InvalidOperationException(
"Unable to locate Contains");
var row = Expression.Parameter(typeof(T), "row");
var member = Expression.Invoke(selector, row);
var values = Expression.Constant(keys, typeof(IEnumerable<TValue>));
var predicate = Expression.Call(method, values, member);
var lambda = Expression.Lambda<Func<T, bool>>(
predicate, row);
return source.Where(lambda).ToList();
}
推荐阅读
- django - django表单的两阶段提交
- codeigniter - 页码 url 分页 CodeIgniter
- python - 我正在尝试登录 discord 但我收到错误代码
- javascript - FullCalendar React - 如何将 selectConstraint 与 Display Background & Inverse 的背景事件一起使用
- python - Pickle Telethon 消息抛出“无法腌制 '_asyncio.Future' 对象”
- sql-server - 如何根据前一行获取下一行值,不包括 SQL Server 中的周末?
- javascript - 滚动元素内 HTML 元素的边界矩形
- google-cloud-platform - GCP PubSub 长轮询
- angular - 我应该如何根据 Angular 中的 Cookie 设置来管理模块的加载?
- autodesk-forge - Autodesk Forge Viewer - 近端和远端剪裁问题