动态LINQ表达式
本文关键字:表达式 LINQ 动态 | 更新日期: 2023-09-27 18:04:22
我想实现这个如何在Linq where子句中指定动态字段名称?并得到一个编译错误,说:
无法解析方法'Where(System.Linq.Expressions.LambdaExpression
public class Employee
{
public string Name { get; private set; }
public int Salary { get; private set; }
public Employee(string name, int salary)
{
Name = name;
Salary = salary;
}
}
然后在控制台应用程序的main方法
var employees = new List<Employee>
{
new Employee("Bob", 45000),
new Employee("Jane", 25000),
new Employee("Jim", 5)
};
var eParam = Expression.Parameter(typeof(Employee), "e");
var comparison = Expression.Lambda(
Expression.LessThan(
Expression.Property(eParam, "Salary"),
Expression.Constant(40000)),
eParam);
var c = from e in employees.Where(comparison) // COMPILER ERROR HERE!!!
select new {e.Name, e.Salary};
我使用System.Linq
和System.Linq.Expressions
。我哪里做错了?
答案是强类型比较变量并像
那样调用Compilevar comparison = Expression.Lambda<Func<Employee, bool>>(
Expression.GreaterThan(
Expression.Property(eParam, "Salary"),
Expression.Constant(40000)),
eParam).Compile();
查询也可以用方法语法编写,如
var b = employees.Where(comparison);
可以在.Where()
之前调用.AsQueryable()
,而不是调用.Compile()
。
-
表达式必须是强类型的:
var comparison = Expression.Lambda<Func<Employee, bool>>(...
-
Source必须为
IQueryable
。呼叫Where前先呼叫列表中的AsQueryable()