[英]Get value from expression in linq extension method
我搜寻了整个互联网并尝试了许多方法,但是我无法从表达中获得价值。 如果有人可以帮助我,那将非常酷。
再见马库斯
public static class LinqExtension
{
public static IQueryable<T> GetFilteredByStatusList<T>(this IQueryable<T> source, Expression<Func<T, int>> expression)
{
// So I can compile the expression.
// In some posts I have found, that I have to call the compiled method, but the method needs the T object.
// I have no idea how to acces the value of T.
Func<T, int> method = expression.Compile();
//EDIT
// Here I need the int value to pass it in a service method like:
// Service.GetStatusById("int value from expression");
//EDIT END
return source;
}
}
-编辑我有一个查询,在此查询中,我必须调用一个需要当前查询项具有动态值的方法。 该方法已经存在,在使用for循环的查询进行查询后,可以使该方法起作用,并在此循环中的每个项目上调用此方法。 但是我认为这不是一个很快的解决方案。
因此,我在查询中调用此方法,这就是为什么我尝试使用扩展方法来实现此方法。
遵循扩展方法调用:
return query = query
.Join(entities.tblTaskgroupGlobal, x => x.lngAssignMain_id, y => y.id, (x, y) => new { x = x, y = y })
.WhereIf(taskFilterModel.StatusFilterList.Count() > 0, xy => taskFilterModel.StatusFilterList.Contains(xy.y.lngConstantStatus_id))
.GetFilteredByStatusList(xy => xy.x.lngAssignMain_id)
.Select(xy => xy.x);
-编辑结束
哇,整个互联网! 那一定花了一段时间! :)
现在,您已编译的表达式期望采用T类型的对象并返回int类型的值。
我想您想枚举source
并将其method
应用于它。
例如:
foreach (T item in source)
{
yield return method(item);
}
但我认为更好的问题是-您打算如何使用此方法? 您确定表达式是您所需要的吗?
最简单的解决方案是:
返回source.Select(表达式);
但是话又说回来,如果那是您真正想要的,那么您根本不需要编写自己的GetFilteredByStatusList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.