Join Predicate的默认值为方法参数

时间:2015-09-21 20:19:23

标签: linq linq-to-entities

我有一个选择数据的方法。如果调用者可以提供谓词来修改.Where(),它可以支持多个用例。我试过像

这样的东西
private class ABJoin
{
    public A A { get; set; }
    public B B { get; set; }
}

bool NoFilter(ABJoin join, int index)
{
    return true; // Don't filter at all for this
}

private IEnumerable<TResult> GetData
(Func<ABJoin, int, bool> filter)
{
    var query = ctx.TypeA
        .Join(ctx.TypeB, a => a.BId, b => b.Id, 
              (a, b) => new ABJoin() { A = a, B = b })
    // etc.
}

到目前为止效果很好。

但是,某些用例不需要提供任何过滤器(真实版本具有其他参数来区分每个用例的行为)。我认为为过滤器参数

提供默认值会很方便
private IEnumerable<TResult> GetData
(Func<ABJoin, int, bool> filter = NoFilter)

然而,这不编译。该错误指出NoFilter必须是编译时常量。

有没有办法在filter中为GetData()提供默认值?

1 个答案:

答案 0 :(得分:2)

提供默认值null并将其与方法中的真实委托交换:

private IEnumerable<TResult> GetData(Func<ABJoin, int, bool> filter = null)
{
    filter = filter ?? ((a,b) => true);
}