动态LINQ表达式 [英] Dynamic LINQ Expression

查看:61
本文介绍了动态LINQ表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实施此

I'm trying to implement this How to specify dynamic field names in a Linq where clause? and getting a compiler error that says:

无法解析方法'Where(System.Linq.Expressions.LambdaExpression

Cannot resolve method '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;
    }
}

然后进入控制台应用程序的主要方法

Then in main method of console app

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.LinqSystem.Linq.Expressions.我在这里做什么错了?

I'm using System.Linq and System.Linq.Expressions. What am I doing wrong here?

答案是强烈键入比较变量,然后像这样调用Compile

The answer is to strongly type the comparison variable and call Compile on it like

var comparison = Expression.Lambda<Func<Employee, bool>>(
    Expression.GreaterThan(
        Expression.Property(eParam, "Salary"),
        Expression.Constant(40000)),
    eParam).Compile();

查询也可以用方法语法编写,例如

The query can also be written in method syntax like

var b = employees.Where(comparison);

除了呼叫.Compile(),还可以在员工的.Where()之前呼叫.AsQueryable().

Instead of calling .Compile(), one can call .AsQueryable() before .Where() on employees also.

推荐答案

  1. 您的表达式必须为强类型:

  1. Your expression has to be strongly typed:

var comparison = Expression.Lambda<Func<Employee, bool>>(... 

  • 源必须为IQueryable.在呼叫位置之前,先呼叫列表中的AsQueryable().

  • Source has to be IQueryable. Call AsQueryable() on your list before calling Where.

    这篇关于动态LINQ表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆