Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reuse expressions within LINQ statements?

Tags:

c#

lambda

linq

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?

like image 570
CVertex Avatar asked Jun 12 '09 14:06

CVertex


People also ask

What is System LINQ expression?

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.

What are LINQ query expressions?

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.

How many ways can you write LINQ queries?

LINQ provides you three different ways to write a LINQ query in C# or VB.

What is return in LINQ?

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.


1 Answers

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()}; 
like image 149
Garry Shutler Avatar answered Oct 14 '22 06:10

Garry Shutler