How do I create this expression tree (dynamic lambda) in C#?

c# dynamic-linq linq

Question

I am trying to create an expression tree (dynamic linq) that represents the following: There are my custom classes and collections.

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

Here my classes:

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;

Thank you...

1
0
2/5/2013 2:20:50 PM

Popular Answer

Are you trying to consolidate your expression tree into a single delegate? If so, here is an example:

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();

Hope this helps!

0
2/5/2013 3:13:39 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow