0

我正在尝试对对象列表进行排序,我在网上搜索,但我不明白为什么它不起作用。

这是我的域类,其中包含我要排序的列表:

class MyClass {
    Integer bar
    static hasMany = [**foos : Foo**]
}

对象 Foo 看起来像这样:

class Foo {
    LocalDate day
    String name
}

我想按日期对 foos 进行排序。所以我试着写:

MyClass myClass = new MyClass()
//foos contains 10 days.
myClass.foos = myClass.foos.sort { it.day }

我不明白错误在哪里以及为什么我的列表没有正确排序。有人可以帮忙吗?

谢谢。

4

3 回答 3

5

hasManySet默认情况下由 a 支持。尝试将其更改为 a List,例如:

class MyClass {
    Integer bar
    List foos
    static hasMany = [foos : Foo]
}
于 2013-03-25T11:04:57.927 回答
3

默认情况下,您有两种选择如何对对象进行排序。两者都在可排序类中:

  1. (对于简单的排序算法):

    static mapping = {
        sort 'dateCreated':'desc'
    }
    
  2. (对于复杂的排序算法,您使用一个函数):

    class Target implements Comparable {
    
    ...
    
        int compareTo(o) {
    
            if(o instanceof Target) {
                Target t = (Target) o
                // sort multidimensional
                return (this.target_definition_order <=> t.target_definition_order ?:
                this.target_order <=> t.target_order )
            } else
                return 0
        }
    
    }
    

您的问题可能是特殊类的排序算法LocalDate

于 2013-03-25T10:32:53.233 回答
0

如果您使用 Date 对象而不是 LocalDate,则使用您提供的代码进行排序。

        use(TimeCategory) {
            MyClass myClass = new MyClass(bar: 1)
            Date today = new Date()
            def foo = new Foo(name: "a", day: today)
            myClass.addToFoos(foo)
            myClass.save(flush: true)
            foo = new Foo(name: "a", day: today+1.second)
            myClass.addToFoos(foo)
            foo = new Foo(name: "a", day: today+2.second)
            myClass.addToFoos(foo)
            foo = new Foo(name: "a", day: today+3.second)
            myClass.addToFoos(foo)
            foo = new Foo(name: "a", day: today+4.second)
            myClass.save(flush: true)
        }

使用 myClass.foos.sort{it.date} 或 myClass.foos.sort{it.date}.reverse() 会给出正确的结果。

于 2013-03-25T10:37:15.187 回答