如何在C#中创建这个表达式树(动态lambda)?

时间:2013-02-05 14:20:51

标签: c# linq dynamic-linq

我正在尝试创建一个表示以下内容的表达式树(动态linq):有我的自定义类和集合。

List<Contract> sel = contractList.Where(s => s.account.Age > 3 && s.productList.Any(a => a.ProductType == "abc")).ToList();

这是我的课程:

public class Account
{
    public int Age { get; set; }
    public decimal Balance { get; set; }

    public Account(int Age, decimal Balance)
    {
        this.Age = Age;
        this.Balance = Balance;
    }
}

public class Product
{
    public string ProductType { get; set; }

    public Product(string ProductType)
    {
        this.ProductType = ProductType;
    }
}

public class Contract
{
    public int ID { get; set; }
    public Account account { get; set; }
    public List<Product> productList { get; set; }
    public Contract(int ID, Account account, Product product, List<Product> productList)
    {
        this.ID = ID;
        this.account = account;
        this.productList = productList;
    }
}

public List<Contract> contractList;

谢谢...

1 个答案:

答案 0 :(得分:0)

您是否尝试将表达式树合并为一个委托?如果是这样,这是一个例子:

public static bool IsOlderThanThreeAndHasAbcProductType(Contract contract)
{
    if (contract.account.Age > 3
        && contract.productList.Any(a => a.ProductType == "abc"))
    {
        return true;
    }
    return false;
}

List<Contract> sel = contractList.Where(IsOlderThanThreeAndHasAbcProductType).ToList();

希望这有帮助!