I like to reuse expressions for DRY reasons, but how do I reuse the expressions within a LINQ statement?
e.g.
I have
public static class MyExpressions { public static Expression<Func<Product,bool>> IsAGoodProduct() { return (p) => p.Quality>3; } }
And would like to use that in LINQ statements, so
var goodProds = from p in dataContext.Products where ????? // how do I use IsAGoodProduct here? select p;
Sure, I could use the IQueryableExtension.Where function, but that would make joins and other functions alot uglier for more complex queries.
Is this possible or is it a limitation of LINQ?
Expression. Provides the base class from which the classes that represent expression tree nodes are derived. It also contains static ( Shared in Visual Basic) factory methods to create the various node types. This is an abstract class.
Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.
LINQ provides you three different ways to write a LINQ query in C# or VB.
Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.
If you move from the LINQ syntactic sugar it is possible:
var goodProds = dataContext.Products.Where(MyExpressions.IsAGoodProduct());
Without it, it isn't possible.
There's nothing to stop you mixing the two styles to build a single query though.
Example:
var goodProds = from p in dataContext.Products .Where(MyExpressions.IsAGoodProduct()) group p by p.Category into g select new {Category = g.Key, ProductCount = g.Group.Count()};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With