如何使用非通用 Lambda 生成子查询
您如何将以下通用 Lambda 函数转换为 lambda 表达式:
context.AssociateWith<Product>(p => p.Regions.Where(r => r.Country == 'Canada')
我正在尝试创建一个完整的 lambda 表达式,而无需任何
或直接调用。类似的东西:
void AddFilter(ITable table, MetaDataMember relation)
{
var tableParam = Expression.Parameter(table.ElementType, "e");
var prop = Expression.Property(tableParam, relation.Name);
var func = typeof(Func<,>).MakeGenericType(table.ElementType, relation.type)
var exp = Expression.Lambda(func, prop, tableParam);
}
这将产生 e.Regions
...但我无法从那里获取 Where
部分...
How would you translate the following generic Lambda function into a lambda expression :
context.AssociateWith<Product>(p => p.Regions.Where(r => r.Country == 'Canada')
I'm trying to create a full lambda expression without any <T>
or direct call. Something like :
void AddFilter(ITable table, MetaDataMember relation)
{
var tableParam = Expression.Parameter(table.ElementType, "e");
var prop = Expression.Property(tableParam, relation.Name);
var func = typeof(Func<,>).MakeGenericType(table.ElementType, relation.type)
var exp = Expression.Lambda(func, prop, tableParam);
}
This will produce e.Regions
... but I'm unable to get the Where
part from there...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道我的答案已经很晚了,可能这不是您正在寻找的确切解决方案(仍然经常使用),但也许它会帮助您和其他人建立他们的表达:
基于此处发布的答案:动态创建包含子查询的 Linq 表达式。
I know I'm very late in the game with my answer and likely this is not the exact solution you are looking for (still uses the frequently), but maybe it will help you and others building their expression:
Based on an answer posted here: Creating a Linq expression dynamically containing a subquery.
试试这个,它并不漂亮,但它为您提供了整个结构的有效表达式。您可以将内部 lambda 定义为表达式,但在将其传递给
Where()
之前您仍然需要对其进行编译,因此就本答案而言,它似乎是多余的。Try this, it's not pretty but it gives you a valid expression for the whole structure. You could define the inner lambda as an expression but you would still have to compile it before you could pass it to
Where()
, so for the purposes of this answer it seems redundant.