如何使用参数重用 LINQ Select 表达式

Amm*_*han 4 c# linq lambda

我编写了一个 LINQ 查询,并为 Select 子句创建了一个表达式来重用它。

我的查询看起来像这样

 DataContext.Single.Select(SearchSelector).ToList();
Run Code Online (Sandbox Code Playgroud)

其中搜索选择器定义为

 private Expression<Func<Singles, SearchSingles>> SearchSelector = s =>
    new SearchSingles
    {
    };
Run Code Online (Sandbox Code Playgroud)

以上工作正常,但如果我想使用两个输入参数怎么办?我将如何调用它?

 private Expression<Func<Singles,string, SearchSingles>> SearchSelector = (s,y) =>
    new SearchSingles
    {
    };
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 5

与其有一个存储表达式的字段,不如有一个方法来创建您需要给定特定字符串的表达式:

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

然后你可以像这样使用这个方法:

DataContext.Single.Select(CreateSearchSelector("Foo")).ToList();
Run Code Online (Sandbox Code Playgroud)