42

我试图在列表中使用 findAll 构建动态过滤器。我有一个变量,只有在不为空时才需要包含在过滤器中。

 @Test
    void testSample(){
        def list = [ new Employee(age:22, isManager:false), 
                     new Employee(age:23, isManager:true), 
                     new Employee(age:22, isManager:true) ] as Set

        def var = 22;
        String query1 = "it.age == var && it.isManager == true "
        String query2 = "it.isManager == true"

        println list
        println list.findAll { var ? query1 : query2 } // Should give 1 record age = 22 and manager
        var = null;
        println list.findAll { var ? query1 : query2 } // should give 2 records-only manager

    }

他们俩都提供了所有记录。无论如何我可以在一种情况下实现这一点而无需编写多个查询?

看起来像下面的(虽然这不起作用)

println list.findAll{
                if(var) it.age == var &&
                it.isManager == true
        }
4

1 回答 1

49

尝试使用闭包而不是描述您想要做什么的字符串:

def list = [ new Employee(age:22, isManager:false), 
             new Employee(age:23, isManager:true), 
             new Employee(age:22, isManager:true) ] as Set

def var = 22;
Closure query1 = { it.age == var && it.isManager == true }
Closure query2 = { it.isManager == true }

println list
println list.findAll( var ? query1 : query2 ) // Should give 1 record age = 22 and manager
var = null;
println list.findAll( var ? query1 : query2 ) // should give 2 records-only manager

编辑

你的意思是:

println list.findAll{ ( var ? it.age == var : true ) && it.isManager == true }

或更好:

println list.findAll{ ( var != null ? it.age == var : true ) && it.isManager == true }
于 2013-08-08T21:48:44.130 回答