How to reuse LINQ Select Expression with arguments

I am writing a LINQ query and for the Select clause I have created a reusable expression.

My request looks like this

 DataContext.Single.Select(SearchSelector).ToList();

      

Where as the Search Selector is defined as

 private Expression<Func<Singles, SearchSingles>> SearchSelector = s =>
    new SearchSingles
    {
    };

      

The above works great, but what if I want to use two input parameters? How can I call it?

 private Expression<Func<Singles,string, SearchSingles>> SearchSelector = (s,y) =>
    new SearchSingles
    {
    };

      

+3


source to share


2 answers


Instead of having a field that stores an expression, use a method that creates an expression that you need to specify for a specific string:

private static Expression<Func<Singles, SearchSingles>> CreateSearchSelector(
    string foo)
{
    return s =>
        new SearchSingles
        {
            Foo = foo,
        };
}

      



Then you can use this method like this:

DataContext.Single.Select(CreateSearchSelector("Foo")).ToList();

      

+3


source


how to leave one signature and pass additional parameters as captured values? It can be of limited use as an initialized member variable like this, but if you assign some kind of work function from within instead of initializing it during class construction, you have more power.

private Func<Singles, SearchSingles> SearchSelector = s =>
    new SearchSingles
    {
         someVal = capturedVariable,
         someOther = s.nonCapturedVar
    };

      

which would work if it capturedVariable

was 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 can have all kinds of entertainment

* EDIT * links to Expression removed and clarified

0


source







All Articles