A.B.Where(extExp).Count() > 0”,我对如何为 Where(...) 进行表达式有疑问因为我假设 ICollection<> 的扩展方法-6ren">
gpt4 book ai didi

c# - 使用 "where"方法调用的表达式

转载 作者:行者123 更新时间:2023-11-30 17:46:43 25 4
gpt4 key购买 nike

我正在尝试实现这种表达式:“A => A.B.Where(extExp).Count() > 0”,我对如何为 Where(...) 进行表达式有疑问因为我假设 ICollection<> 的扩展方法。有人可以帮忙吗?

Expression<Func<N, bool>> conditions = c => c.T_ID == 1 || c.T_ID == 2;
ParameterExpression mpe = Expression.Parameter(typeof(T), "A");
Expression prop = Expression.Property(mpe,typeof(T).GetProperty("B"));
...
var propWhere = Expression.Call(..., prop, conditions);

如何正确调用它

最佳答案

那里有一个采用 MethodInfo 的调用重载。要获取方法信息,我认为最好使用此答案中的代码 - https://stackoverflow.com/a/21060046/122507

public static MethodInfo GetMethodInfo(Expression<Action> expression)
{
var member = expression.Body as MethodCallExpression;

if (member != null)
return member.Method;

throw new ArgumentException("Expression is not a method", "expression");
}

用法

var whereMethodInfo = GetMethodInfo(() => Enumerable.Where(Enumerable.Empty<T>(), i=>true));

顺便说一句,我建议您下载 LINQPad 并使用它来编写查询并查看生成的表达式树和 IL 代码。

关于c# - 使用 "where"方法调用的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com