Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse of a LINQ query

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

like image 201
Blaatz0r Avatar asked Dec 17 '15 14:12

Blaatz0r


1 Answers

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); 
like image 50
Hamid Pourjam Avatar answered Oct 01 '22 16:10

Hamid Pourjam