如何将Linq staement传递给另一种类型?

Tru*_*an1 0 .net c# linq linq-expressions

下面我有一个包装另一个方法的方法.我想要做的是提供一个可选参数来过滤内部方法,这是一种与T不同的类型.

这是被认为是"公共"API的外部方法:

public override IQueryable<T> GetEverything()
{
    return Get()
        .Where(i => i.Active == true)
        .Select(i => new T(i));
}
Run Code Online (Sandbox Code Playgroud)

作为伪代码,我想做这样的事情:

var items = GetEverything(x => x.SomeValue > 10);
Run Code Online (Sandbox Code Playgroud)

哪个会像这样传递给方法

   public override IQueryable<T> GetEverything(???)
    {
        return Get()
            .Where(i => i.Active == true)
            .Where(x => x.SomeValue > 10)
            .Select(i => new T(i));
    }
Run Code Online (Sandbox Code Playgroud)

注意我仍然想保留我的i.Active过滤器,如果开发者决定传入过滤器,我不想放松它.传入的过滤器将不会替换内部过滤器.有人能帮忙吗?任何帮助或建议将不胜感激!

D S*_*ley 5

只需看看签名Queryable.Where:

public static IQueryable<TSource> Where<TSource>(
    this IQueryable<TSource> source,
    Expression<Func<TSource, bool>> predicate
)
Run Code Online (Sandbox Code Playgroud)

所以为了将参数传递给Where最简单的方法是要求Expression<Func<TSource, bool>>:

public override IQueryable<T> GetEverything(Expression<Func<T, bool>> predicate)
{
    return Get()
        .Where(i => i.Active == true)
        .Where(predicate)
        .Select(i => new T(i));
}
Run Code Online (Sandbox Code Playgroud)

请注意,大多数查询提供程序都可以将哪些表达式转换为基础存储查询,因此您可能会通过为过滤器打开一扇门来遇到更多运行时错误.

如果你想保留一个方法并允许一个null谓词,你可以只链接Linq表达式:

public override IQueryable<T> GetEverything(Expression<Func<T, bool>> predicate = null)
{
    var query = Get().Where(i => i.Active == true);

    if(predicate != null)
        query = query.Where(predicate);

    return query.Select(i => new T(i));
}
Run Code Online (Sandbox Code Playgroud)