How can I reuse expressions within LINQ statements?

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?

--------------Solutions-------------

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

We had the same problem. It is not supported out of the box and it is a major problem for LOB applications. I ended up writing a code-project article about LINQ expressions reuse, including a very small utility called LinqExpressionPrjection that enables the reuse in projections (including into anonymous types).

Find the article here.

You can get the assembly for the projection reuse as a nuget package and the source is on CodePlex.

Some time has passed since your post. I hope it is still helpful for you. If not, maybe for others reading this thread.

I had the same problem and wanted to preserve the ability to use extension methods within the query syntax (as with ordinary supported functions...). A solution might be this library.

You just implement the method to reuse twice, once for general use and once for queries.

public static class MyFunctions {
[InjectLambda]
public static bool IsAGoodProduct(Product product) {
return product.Quality>3;
}
public static Expression<Func<Product,bool>> IsAGoodProduct() {
return (p) => p.Quality>3;
}
}

The actual query can then look like expected.

var goodProds = from p in dataContext.Products.ToInjectable()
where p.IsAGoodProduct()
select p;

The ToInjectable call creates a lightweight proxy, which replaces the IsAGoodProduct method call (if marked accordingly) with the desired lambda expression. Thus, you can use extension methods wherever within the query -- parameterized methods work as well.

By the way, I've come across this useful article which explains how you can create dynamic LINQ Queries that reference functions wrapped as Expressions using a custom ToExpandable() extension method. The solution provided can be used within the various parts of a LINQ Query all while preserving the use of comprehension syntax instead of resorting to lambda syntax.

Category:c# Time:2009-06-12 Views:1
Tags: c# linq lambda

Related post

  • Reusing Expression in Linq select clause (query format) 2010-07-15

    I have an Expression that converts one type of object to another type. The expression is as follows: public Expression<Func<SQLRepository.ActionType, Model.ActionType>> DBActionTypeToActionType = (SQLRepository.ActionType at) => new Mo

  • How can I use external expressions in Linq with EF4 (and LINQKit)? 2010-03-30

    I want to separate out often used expressions in linq queries. I'm using Entity Framework 4 and also LINQKit but I still don't know how I should do it the right way. Let me give you an example: Article article = dataContainer.Articles.FirstOrDefault(

  • How do I convert this expression to LINQ? 2011-02-25

    Is it possible to convert this expression to LINQ? TermsOfPayment termsOfPayment = null; foreach (CustomerGroup group in _customer.CustomerGroups) if (termsOfPayment == null) termsOfPayment = group.TermsOfPayment; else if (group.TermsOfPayment != nul

  • How to simulate regular expressions in LINQ-to-SQL 2011-04-19

    I have a database table with customer account numbers. Within the same table are test accounts that don't match the production formatting: say, 'A1111' is production but 'JTest' is not. I have the Regex that will pull only my production accounts. I n

  • Converting query expression to Linq method syntax 2011-09-29

    I use EF 4 and C#. I have a query like: var contentsAuthor = from c in context.CmsContents join a in context.CmsAuthors on c.AuthorId equals a.AuthorId where a.UserId == userGuid select new { c.Title, c.ContentId }; I would like rewrite it in Linq wi

  • How to reuse part of Linq to Entity Select expression in EF4.1 code only scenario 2011-06-08

    Here is very simplified version of code that i have: class PrintJob : IEntity { public string UserName { get; set; } public string Departmen { get; set; } public int PagesPrinted { get; set; } } class PrintJobReportItem { public int TotalPagesPrinted

  • converting group SQL expression into LINQ 2009-05-19

    I am having a real pain in converting this query expression into my LINQ expression. SELECT r.Disc_code ,r.SEX FROM RACE r WHERE r.EVENT_CODE = 100 GROUP BY r.SEX , r.disc_Code order by r.disc_code i can work with one table but i have not seen any ex

  • Need help turning this LINQ expression into LINQ statement 2009-10-28

    I need help in turning this linq expression into a linq statment. SampleData.Publishers and SampleData.Books are simple collections that I have from the Linq in Action book. Here is the expression var pubBooks = from pub in SampleData.Publishers join

  • Custom Expression in Linq-to-Sql Designer 2010-05-03

    According to Microsoft: http://msdn.microsoft.com/de-de/library/system.data.linq.mapping.columnattribute.expression.aspx It's possible to add expression to the Linq-to-SQL Mapping. But how to configure or add them in Visual Studio in the Designer? Pr

  • Using lambda expressions and linq 2010-05-19

    So I've just started working with linq as well as using lambda expressions. I've run into a small hiccup while trying to get some data that I want. This method should return a list of all projects that are open or in progress from Jira Here's the cod

  • How can I create a dynamic select expression in LINQ? 2010-07-16

    What I currently have looks a bit like this: if(userLikesBananas) { return from fruit in basket select new Fruit { AteBanana = Bowl.Any(b => b.OwnedBy == user && b.Contains(fruit) && fruit.Type == FruitType.Banana), ... ... //lots

  • C# lambda expression in LINQ query 2010-08-20

    I know that lambda expressions within loops can cause problems if they use local variables. ( see http://www.jaylee.org/post/2008/11/18/Lambda-Expression-and-ForEach-loops.aspx ) Now I have a situation, where I am using a lambda expression within a L

  • How do I express this LINQ query using the NHibernate ICriteria API? 2010-10-29

    My current project is using NHibernate 3.0b1 and the NHibernate.Linq.Query<T>() API. I'm pretty fluent in LINQ, but I have absolutely no experience with HQL or the ICriteria API. One of my queries isn't supported by the IQueryable API, so I pre

  • How can I combine multiple refactored Select expressions in Linq (to EF or SQL)? 2010-11-15

    Say I have this view model: public class SeriesLinkViewModel { public static Expression<Func<Series, SeriesLinkViewModel>> FromSeries = s => new SeriesLinkViewModel { Name = s.Name, Slug = s.Slug, }; public string Name { get; set; } pu

  • SQL query to lambda expression or linq 2011-03-14

    How can I convert the following query to a lambda expression select * from Invoice_main where id not in (select invoice_main_id from Invoice_payment_by_pay_method) I could not find an alternative for 'not in'. --------------Solutions------------- Ass

  • Create an OrderBy Expression for LINQ/Lamda 2011-04-23

    I'm creating a proof of concept that uses Labmda/LINQ for dynamic where and orderby. The following code works for the where expression, but I can not figure out how to create an order by expression. For this exmample, if possible I would like to keep

  • Entity Framework, Enum Support: Modify Expression in Linq Extension Method 2011-06-01

    I'm attempting to implement Entity Framework and I need enum support, so I'm trying to piggy-back off of what is outlined in this blog: http://rogeralsing.com/2010/11/10/entity-framework-4-enum-support-in-linq/. I need to take this a step further bec

  • Parenthesis Expressions in LINQ to SQL 2011-06-27

    If I want to generate the query (month(created) = 1 and year(created) = 2010) or (month(modified) = 1 and year(modified) = 2010) with linq, how would I go about it? I have o.Created.Value.Month == month && o.Created.Value.Year == year. If I d

  • Dynamic Expression using LINQ. How To Find the Kitchens? 2011-08-16

    I try do implement a user dynamic filter, where used selects some properties, selects some operators and selects also the values. As I didn't find yet an answer to this question, I tried to use LINQ expressions. Mainly I need to identify all houses w

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.746 (s). 13 q(s)