Returning values with a Func Delegate

Viewed 112

In an effort to learn more about Func Delegates and Expression trees, I put together a simple example, however I am not getting the results I expect. Below is my code that has a Func that expects a Params class and a List of Products. The idea is to apply the Params Class as a filter against a list of Products. As I said, this is just an exercise for me to learn how all this works.

I am expecting the delegate to return a least one Product object, however it returns null.

static void Main(string[] args)
{
   Products products = CreateProducts();

   Params param = new Params { Val = "ABC"};

   Func<Params, Products, IEnumerable<Product>> filterFunc = 
       (p, r) => r.Where(x => x.Sku == p.Val).AsEnumerable();

   Products prods = filterFunc(param, products).ToList() as Products;// returns null
}


private static Products CreateProducts() 
{
   return new Products 
   {
       new Product{
           Price = 25.00,
           Sku = "ABC"
       },
       new Product{
           Price = 134.00,
           Sku = "DEF"
       }
    };
}

classes:

public class Params 
{
    public String Val { get; set; }
}

public class Products : List<Product> 
{
}

public class Product 
{
    public String Sku { get; set; }
    public double Price { get; set; }
}
3 Answers
Related