LINQ表達式樹

c# expression-trees linq

我想使用以下API生成表達式樹:

var managers = dataContext.Employees.Where(e => e.Subordinates.Any());

另外,如何生成表達式樹來執行此操作:

var managedEmployees = managers.ToDictionary(key => key.Manager, value => value.Subordinates.Select(s => s.FullName));

到目前為止,我已經為.Where()提出了以下內容,但它錯誤,因為它不喜歡new Type[] { typeof(Func<Employee, IEnumerable<Employee>>) }的類型參數。

ParameterExpression employeesParameter = Expression.Parameter(typeof(Employee), "e");
MemberExpression subordinatesProperty = Expression.Property(employeesParameter, typeof(Employee).GetProperty("Subordinates"));
MethodCallExpression hasSubordinates = Expression.Call(typeof(Enumerable),
  "Any",
  new Type[] { typeof(Employee) },
  subordinatesProperty);
LambdaExpression whereLambda = Expression.Lambda(hasSubordinates, employeesParameter);
MethodCallExpression whereExpression = Expression.Call(typeof(Queryable),
  "Where",
  new Type[] { typeof(Func<Employee, IEnumerable<Employee>>) },
  dataContext.Employees.AsQueryable(),
  whereLambda);

一般承認的答案

我懂了。 AnyWhere上的類型參數需要是Employee ,而不是IQueryable<Employee>IEnumerable<Employee>因為它只是查找類型參數,而不是實際類型。我相信你還需要一個Expression.Constant(dataContext.Employees)而不是直接的dataContext.Employees

ParameterExpression employeesParameter = Expression.Parameter(typeof(Employee), "e");
MemberExpression subordinatesProperty = Expression.Property(employeesParameter, typeof(Employee).GetProperty("Subordinates"));

MethodCallExpression hasSubordinates = Expression.Call(typeof(Enumerable),
    "Any",
    new Type[] { typeof(Employee) },
    subordinatesProperty);
LambdaExpression whereLambda = Expression.Lambda(hasSubordinates, employeesParameter);
MethodCallExpression whereExpression = Expression.Call(typeof(Queryable),
    "Where",
    new Type[] { typeof(Employee) },
    Expression.Constant(dataContext.Employees),
    whereLambda);

熱門答案

要為您的MemberExpression調用Any ,您應該這樣做

ParameterExpression employeesParameter = Expression.Parameter(typeof(Employee), "e");
MemberExpression subordinatesProperty = Expression.Property(employeesParameter, typeof(Employee).GetProperty("Subordinates"));

var mi = typeof(Enumerable).GetMethods().First(x => x.Name == "Any" && x.GetParameters().Length == 1);
mi = mi.MakeGenericMethod(typeof (bool));
var hasSubordinates = Expression.Call(mi, subordinatesProperty);

Where

var lambda = Expression.Lambda<Func<Employee, bool>>(hasSubordinates, employeesParameter);
var res = i.Where(lambda.Compile());


許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow