gpt4 book ai didi

c# - ICollection.Any(Func) 的表达式

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

假设我有以下模型:

public class Department
{
public ICollection<Employee> Employees { get; set; }
}

public class Employee
{
public string Name { get; set; }
}

我想为此构建一个表达式:

departments.Where(x => x.Employees.Any(y => y.Name.Contains("foo")))

我有以下代码:

var departmentParameterExpression = Expression.Parameter(typeof(Department), "x");
PropertyExpression departmentListProperty = { x.Departments } // Value of the Expression shown in the debugger, actual code is some property helper to get the property by Name
var employeeParameterExpression = Expression.Parameter(typeof(Employee), "y");
PropertyExpression employeeNameProperty = { y.Name } // Same as departmenListProperty
var employeeNameContainsString = Expression.Call(employeeNameProperty, typeof(string).GetMethod("Contains"), Expression.Constant(token));
var compiledExpression = Expression.Lambda<Func<Employee, bool>>(employeeNameContainsString, employeeParameterExpression).Compile();

var anyMethod = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(x => x.Name == "Any" && x.GetParameters().Length == 2 && x.GetGenericArguments().Length == 1).MakeGenericMethod(typeof(Employee));

var containsEmployeeWithSearchString = Expression.Call(departmentListProperty, anyMethod, Expression.Constant(compiledExpression);

运行最后一行,出现以下错误:

静态方法需要空实例,非静态方法需要非空实例。参数名称:实例

不幸的是,当我只有 .GetMethods(BindingFlags.Static) 时,我没有得到任何 Any()-Method。

我如何使它工作?

最佳答案

AnyWhereEnumerable 的扩展方法,因此根据定义是 static。您尝试构建的实际 表达式将等效于:

Enumerable.Where(departments, 
x => Enumerable.Any(x.Employees,
y => y.Name.Contains("foo")
)
)

关于c# - ICollection<T>.Any(Func<T, bool>) 的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41244711/

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