How to reuse LINQ Select Expression with arguments

2019-05-15 12:54发布

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
    {
    };

标签: c# linq lambda
2条回答
趁早两清
2楼-- · 2019-05-15 13:17

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

查看更多
看我几分像从前
3楼-- · 2019-05-15 13:22

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();
查看更多
登录 后发表回答