按时间戳和枚举排序列表。

huangapple go评论55阅读模式
英文:

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&lt;InboxItem&gt; { 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&lt;InboxItem&gt; { 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.

huangapple
  • 本文由 发表于 2023年7月3日 14:59:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定