Suppose I have the two following Linq queries I want to refactor:
var someValue1 = 0;
var someValue2= 0;
var query1 = db.TableAs.Where( a => a.TableBs.Count() > someValue1 )
.Take( 10 );
var query2 = db.TableAs.Where( a => a.TableBs.First().item1 == someValue2)
.Take( 10 );
Note that only the Where parameter changes. There is any way to put the query inside a method and pass the Where parameter as an argument?
Yeah, the parameter type is a lamba expression
Func<TSource, bool>
You can do it the same way you'd refactor any other code:
where T and U are whatever types ar erelevant in your query.
You can using
Predicate<T>
.The just call it like that.
And give a better namen than
Helper
.Of couse there is. The where parameter is just a simple closure of type
Func<T, bool>
(where T is the type of your DB items - I don't know them out of your code) and you can wrap it into a (anonymous) function.Use it like this