Reputation: 2585
I write a LINQ query and for Select clause I created an Expression to reuse it.
My query looks like this
DataContext.Single.Select(SearchSelector).ToList();
Where as Search Selector defined as
private Expression<Func<Singles, SearchSingles>> SearchSelector = s =>
new SearchSingles
{
};
The above works fine, but what if I want to use two input parameters? How would I invoke it?
private Expression<Func<Singles,string, SearchSingles>> SearchSelector = (s,y) =>
new SearchSingles
{
};
Upvotes: 4
Views: 3758
Reputation: 312
what about leaving the signature alone and passing additional parameters as captured values? It might have limited use as an initialized member variable, like this, but if you assign from within some worker function, rather than initialize it during class construction you'd have more power.
private Func<Singles, SearchSingles> SearchSelector = s =>
new SearchSingles
{
someVal = capturedVariable,
someOther = s.nonCapturedVar
};
that would work if capturedVariable
were a static member
or
private Func<Singles, SearchSingles> SearchSelector = null;
private void WorkerFunction(string capturedVariable, bool capAgain, bool yetAgain)
{
SearchSelector = s => {
bool sample = capAgain;
if (capturedTestVar)
sample = yetAgain;
return new SearchSingles
{
someVal = capturedVariable,
someOther = s.nonCapturedVar,
availability = sample
};
};
};
you could have all sorts of fun
*EDIT* references to Expression removed and clarifications
Upvotes: 0
Reputation: 203821
Rather than having a field that stores the expression, have a method that creates the expression that you need given a particular string:
private static Expression<Func<Singles, SearchSingles>> CreateSearchSelector(
string foo)
{
return s =>
new SearchSingles
{
Foo = foo,
};
}
You can then use this method like so:
DataContext.Single.Select(CreateSearchSelector("Foo")).ToList();
Upvotes: 5