如何在 Kotlin 中使用 Anko 对基于 table 的两个字段进行排序?

How can I sort a table based two fields using Anko in Kotlin?

我用Anko来操作SQLitetable,我希望先根据字段isFavorite对列表进行排序,然后再根据createdDate

例如输入Source Data,得到Sort Result Data

但是代码return myList.sortedBy{it.isFavorite}.sortedBy{ it.createdDate}无法得到正确的结果,我该如何解决?

源数据

排序结果数据(希望得到)

结构

data class MRecord (
    var _id: Long,     
    var isFavorite: Bool,   
    var createdDate: Long
)

代码

var myList=select(tableName).parseList { MDBRecord(HashMap(it)) }        
return myList.sortedBy{it.isFavorite}.sortedBy{ it.createdDate}

添加内容

致疯子:谢谢!

data class MRecord(
    var id: Long,
    var isFavorite: Long,
    var createdDate: Long
)


val list = listOf(
        MRecord(1, 1, 100),
        MRecord(2, 0, 200),
        MRecord(3, 1, 300)
)

希望得到结果

1, 1, 100
3, 1, 300
2, 0, 200

但是代码 println(list.sortedWith(compareBy({ !it.isFavorite }, MRecord::createdDate))) 将不起作用,因为 isFavorite 很长,我该如何解决?

你是对的,myList.sortedBy{it.isFavorite}.sortedBy{ it.createdDate}不会给你正确的结果,因为它基本上等于myList.sortedBy{ it.createdDate}(只适用最后的排序)。你需要的是一个考虑多个字段的比较器,看起来 compareBy 就是你需要的:

Creates a comparator using the sequence of functions to calculate a result of comparison. The functions are called sequentially, receive the given values a and b and return Comparable objects. As soon as the Comparable instances returned by a function for a and b values do not compare as equal, the result of that comparison is returned from the Comparator.

所以,看看这个:

data class MRecord(
    var id: Long,
    var isFavorite: Boolean,
    var createdDate: Long
)

fun main(args: Array<String>) {
    val list = listOf(
        MRecord(1, true, 10),
        MRecord(2, false, 20),
        MRecord(3, true, 30)
    )

    println(list)

    println(list.sortedWith(compareBy({ !it.isFavorite }, MRecord::createdDate)))
}

请注意如何混合使用 lambda 和函数引用。

编辑 Long 最喜欢:

data class MRecord(
    var id: Long,
    var isFavorite: Long,
    var createdDate: Long
)

fun main(args: Array<String>) {
    val list = listOf(
        MRecord(1, 1, 100),
        MRecord(2, 0, 200),
        MRecord(3, 1, 300)
    )

    println(list.sortedWith(compareByDescending<MRecord> { it.isFavorite }.then(compareBy(MRecord::createdDate))))
}