[英]Get value from expression in linq extension method
I searched the whole internet and tried many things, but I am not able to get the value from my expression. 我搜寻了整个互联网并尝试了许多方法,但是我无法从表达中获得价值。 It would be very cool if anybody could help me...
如果有人可以帮助我,那将非常酷。
bye Markus 再见马库斯
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;
}
}
-- EDIT I have a query and in this query I have to call a method which needs a dynamic value from the current query item. -编辑我有一个查询,在此查询中,我必须调用一个需要当前查询项具有动态值的方法。 This method already exists and I get this to work after a the query with a for loop through the query and call this method on every item in this loop.
该方法已经存在,在使用for循环的查询进行查询后,可以使该方法起作用,并在此循环中的每个项目上调用此方法。 But I think this is not a very fast solution.
但是我认为这不是一个很快的解决方案。
So I to call this method inside the query and that is why I try to implement this with an extension method. 因此,我在查询中调用此方法,这就是为什么我尝试使用扩展方法来实现此方法。
Following the extension method call: 遵循扩展方法调用:
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);
-- EDIT END -编辑结束
Wow, the whole internet! 哇,整个互联网! That must have taken a while!
那一定花了一段时间! :)
:)
The expression you have compiled is now expecting to take an object of type T and return a value of type int. 现在,您已编译的表达式期望采用T类型的对象并返回int类型的值。
I would imagine that you want to enumerate source
and apply your method
to it. 我想您想枚举
source
并将其method
应用于它。
For example: 例如:
foreach (T item in source)
{
yield return method(item);
}
But I think the better question is - how are you planning to use this method? 但我认为更好的问题是-您打算如何使用此方法? Are you sure that an Expression is what you need?
您确定表达式是您所需要的吗?
The simplest solution would be: 最简单的解决方案是:
return source.Select(expression); 返回source.Select(表达式);
But then again, if that's what you REALLY wanted to do you wouldn't need to write your own GetFilteredByStatusList
at all. 但是话又说回来,如果那是您真正想要的,那么您根本不需要编写自己的
GetFilteredByStatusList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.