Using methods in LINQ queries / query reuse
I think that LINQ is great work, but there is one big thing that I was missing in it. When you write a query that will be converted to some other representation (either SQL in case of DLINQ, or anything else that can be done using IQueryable) you can't use your own functions in the body of query. There was already question regarding this issue (Query re-use and refactoring - some tips?). Look at the linked question for one example when this might be usefull, another example that I use is situation when I want to share one code that performs some price calculations and use it in more queries in data access layer.
I was trying to implement this since early LINQ versions, but there were several issues, but fortunately the latest May CTP has (almost) everything I needed, so I finally have an working version of library allowing you to write something like this:
// Lambda expression that calculates the priceExpression<Func<Nwind.Product,decimal?>> calcPrice = (p) => p.UnitPrice * 1.19m;// Query that selects productsvarq =frompindb.Products.ToExpandable()where calcPrice.Invoke(p) > 30.0mselect new { p.ProductName, OriginalPrice = p.UnitPrice, ShopPrice = calcPrice.Invoke(p) };Here are the links:
- Article:http://tomasp.net/blog/linq-expand.aspx
- Article in PDF:http://tomasp.net/articles/linq-expand/linq-expand.pdf
- Code samples:http://tomasp.net/articles/linq-expand/demos.zip
I'm looking forward to your comments![]()

