【问题标题】:How to sort by multiple fields in Grails?如何按 Grails 中的多个字段排序?
【发布时间】:2016-01-06 18:10:37
【问题描述】:

我有一个需要按 3 个不同字段排序的列表。如果是查询,我可以执行以下操作:

and {
    invoiceTicketDetail {
        order('date', 'asc')
        order('xrefCode', 'asc')
    }
    order('lineType')
}

但我已经有了如下列表:

List<InvoiceDetail> invoiceDetailList = invoiceHeader.invoiceDetails.findAll {it.deleted==Boolean.FALSE && it.amount!=0} as List

我怎样才能从第一个命令中获得相同的结果?问题是我们有两种不同的方式来显示信息。一个用于在屏幕上打印,一个用于生成报告。它们都必须以相同的顺序显示信息。

【问题讨论】:

  • 我认为只使用标准就会产生更简洁的代码。

标签: grails grails-orm


【解决方案1】:

你可以在你的标准中这样做:

{
  order('date,xrefCode,lineType','asc')
}

或写查询:

Clazz.find("from Clazz order by date,xrefCode,lineType asc")

Clazz 是您的域名

【讨论】:

    【解决方案2】:

    您可以通过...按多个条件(字段、属性等)排序

    1. 比较第一个属性
    2. 如果第一个属性比较结果为 0(这意味着它们相等),则继续下一个属性。否则,考虑对这两个项目进行排序。

    这是一个闭包,可以用属性名称列表进行柯里化,然后传递给Iterable.sort(boolean, Closure)Iterable.toSorted(Closure)

    def sortByProperties = { List propertyNames, Object a, Object b ->
        propertyNames
            .collect { a[it] <=> b[it] }
            .find { it != 0 }
    }
    

    示例

    下面是如何使用闭包。

    def date1 = new Date() + 3
    def date2 = new Date() - 2
    
    def list = [
        [date: date1, xrefCode: 2, lineType: 'b'],
        [date: date2, xrefCode: 2, lineType: 'c'],
        [date: date2, xrefCode: 1, lineType: 'c'],
        [date: date1, xrefCode: 2, lineType: 'a']
    ]
    
    def sortByProperties = { List propertyNames, Object a, Object b ->
        propertyNames
            .collect { a[it] <=> b[it] }
            .find { it != 0 }
    }
    
    // This form requires Groovy >= 2.4
    def sortedList = list.toSorted(sortByProperties.curry(['date', 'xrefCode', 'lineType']))
    
    // An alternative.
    def sortedList = list.sort(false, sortByProperties.curry(['date', 'xrefCode', 'lineType']))
    

    输出如下所示。

    [
        [date:Tue Oct 06 20:13:13 EDT 2015, xrefCode:1, lineType:c], 
        [date:Tue Oct 06 20:13:13 EDT 2015, xrefCode:2, lineType:c], 
        [date:Sun Oct 11 20:13:13 EDT 2015, xrefCode:2, lineType:a], 
        [date:Sun Oct 11 20:13:13 EDT 2015, xrefCode:2, lineType:b]
    ]
    

    【讨论】:

      【解决方案3】:

      嗯,

      我为解决这个问题所做的工作:

      • 创建了我自己的比较器,当我得到列表时,我调用了类似的东西:

      Collections.sort(list, new MyComparator());

      在屏幕上显示之前和生成报告之前。 这解决了我的问题。

      【讨论】:

        猜你喜欢
        • 2010-09-24
        • 2013-04-26
        • 2021-11-03
        • 2020-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多