英文:
Kotlin Sort list by Timestamp and then by enum
问题
我想首先按时间戳(在我的情况下只是一个字符串)对列表进行排序,然后按枚举排序。
仅按时间戳对列表进行排序,我使用以下代码:
list.sortByDescending { it.timestamp }
或者
list.sortWith(compareByDescending<InboxItem> { it.timestamp })
对于枚举,我找到了以下代码:
list.sortBy { it.enum }
我尝试将它们结合起来,但似乎不会按我的枚举值排序。
list.sortWith(compareByDescending<InboxItem> { it.timestamp }.thenBy { it.enum })
有人可以帮我解决这个问题吗?
英文:
I want to sort a list first by timestamp ( just a string in my case) and after that by an enum.
Sorting the list only by timestamp I use
list.sortByDescending { it.timestamp }
or
list.sortWith(compareByDescending<InboxItem> { it.timestamp })
For enum I found:
list.sortBy{it.enum}
I tried to combine both but it does not seem that it will sort by my enum value.
list.sortWith(compareByDescending<InboxItem> { it.timestamp }.thenBy{it.enum})
Can someone help me with this?
答案1
得分: 1
你发布的代码将按照你描述的方式进行排序。请注意,枚举常量的默认排序顺序是按照它们在源文件中的 ordinal(顺序)而不是按照 name(名称)来排序。并且请注意,时间戳的顺序将始终获胜,即使纳秒的差异非常小。
英文:
The code you posted will sort the way you described. Note that the default sorting order of enum constants is by ordinal (the order they are in the source file), not by name. And note that the timestamp order will always win, even if there is a very minor difference of nanoseconds.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论