Reuse of a LINQ query
Asked Answered
H

4

40

This is not about the reuse of a result but more the statement itself. Nor is it about an error when using var as mentioned in: LINQ to SQL: Reuse lambda expression

Out of sheer curiosity I was wondering if it is possible to reuse a single LINQ statement.

Lets say I have the following LINQ statement:

.Where(x => x.Contains(""));

Is it possible to extract the statement x => x.Contains("") and use some kind of reference to this for later usage in, lets say, another class?

So I can call it like: .Where(previouslySavedStatement);

Hardan answered 17/12, 2015 at 14:42 Comment(8)
put it in a variable. Func<string, bool> func = x => x.contains("");Weld
@wudzik This isn't a duplicate. The duplicate reference refers to re-using results, the question asks about re-using the query itself.Biisk
Thanks Shlomo :) just made the edit myselfHardan
@Biisk sorry, missunderstood question, reopenedRegrate
Func<string, bool> previouslySavedStatement = x => x.Contains("") or Expression<Func<string, bool>> if the source is an IQueryable.Christan
Possible duplicate of LINQ to SQL: Reuse lambda expressionTanbark
@RobertMcKee I have looked at the link you posted but the problem there is between var / func<> it can be used to answer my question but in the base it is different. So no 'similairity'Hardan
@Hardan The answer for that and this is the same. The first answer in the link I gave says that for LINQ over SQL (and LINQ over EF) is Expression<Func<Table1, bool>> lambda = x => x.Id > 1000; and Func<Table1, bool> lambda = x => x.Id > 1000; for IEnumerables which is the same as the answer you marked correct. The "base" is the same. IEnumerables take lamdas/delegates, while IQueryables take expressions to build expression trees.Tanbark
T
51

You can store it in a variable. If you are working with IQueryable then use:

System.Linq.Expressions.Expression<Func<Foo, bool>> selector = x => x.Contains("");

If you are using IEnumerable then use:

Func<Foo, bool> selector = x => x.Contains("");

And use it in your query:

query.Where(selector);
Tarsia answered 17/12, 2015 at 14:47 Comment(3)
FYI to @Hardan If you are working with a IEnumerable<T> instead of a IQueryable<T> you would only use Func<Foo, bool> selector = ..., but if you are using IQueryable<T> you most defiantly want to use the Expression<Func<Foo, bool>> version.Idyll
@ScottChamberlain Most of my statements are IEnumerable<T> so thanks for the heads upHardan
@Hardan if you have the expression version you can also convert it in to a delegate by doing Func<Foo, bool> selector2 = selector.Compile();, you can't go the other direction from a delegate to a expression.Idyll
V
7

Yes, you can write a function containing the query you want to reuse, which takes and returns an IQueryable<T>

   public IQueryable<T> ContainsEmpty(IQueryable<T> query)
   {
       return query.Where(x => x.Contains(""));
   }

Now you can reuse it:

   query1 = ContainsEmpty(query1);
   query2 = ContainsEmpty(another);
Vet answered 17/12, 2015 at 15:2 Comment(2)
+1 This does not directly answer OP's question, but it's a much better way of solving his problem (though, why did you choose IQueryable<T> instead of IEnumerable<T>?)Castor
The datatype isn't specified in the question, but it does mention "LINQ to SQL" and has "query" in the title, so I guessed IQueryable :-)Vet
B
5

It depends. There's two Where methods, Enumerable.Where and Queryable.Where. If you're applying the .Where to an IEnumerable than the first one is called, if you're applying it to an IQueryable the second one is called.

Since Enumerable.Where takes in a Func, it isn't reusable. Since Queryable.Where takes in an expression, it is reusable. You can do so as follows:

var x = new List<string>().AsQueryable();

var query = x.Where (n => n.Contains("some string"));

//Extract the lambda clause
var expr = query.Expression;
var methodExpr = (MethodCallExpression)expr;
var quoteExpr = (UnaryExpression)methodExpr.Arguments[1];
var funcExpr = (Expression<Func<string, bool>>)quoteExpr.Operand;

You can then later re-apply the where expression:

var query2 = x.Where(funcExpr);
Biisk answered 17/12, 2015 at 14:59 Comment(2)
Yes, I even read the accepted answer, and I even read the question too. I even believe my answer answers the question as even asked better than the accepted answer even did.Biisk
var methodExpr = (MethodCallExpression)expr; seems less clean than just MethodCallExpression methodExpr = expr;Cherilyncherilynn
E
2

I wrote a library to address exactly this concern, it's called CLinq and you can find an implementation for the EntityFramework here: https://www.nuget.org/packages/CLinq.EntityFramework

It allows to create query snippets and use them everywhere you in a linq query. Following the example of Hamid, create the following expression:

System.Linq.Expressions.Expression<Func<Foo, bool>> selector = x => x.Contains("");

You can now use this query everywhere in your linq queries like this:

query.AsComposable().Where(o => selector.Pass(o));

Additionally to this simple example you're also able to combine your query snippets:

query.AsComposable().Where(o => selector.Pass(o) || anotherSelector.Pass(o));

or even merge them together:

query.AsComposable().Where(o => anotherSelector.Pass(selector.Pass(o)));

There's some more features, but I think it's really helpful, so check it out :)

Exfoliation answered 25/8, 2018 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.