英文:
Reverse chronological order of struct/results
问题
刚开始学习Go语言。
想知道如何在Go中按照结构体元素的逆序进行排序。假设我从数据库中获取到了如下结果:
var results []<someClass>
collection.C(results).Find(bson.M{"<someid>":<id_val>}).All(&results)
现在,我有一个名为results
的切片,其中包含了数据库对象/结果。如何按照名为"time"的列对切片results
进行逆序排序呢?
英文:
Just started learning goLang.
Wondering how can we sort an struct elements in reverse order in Go. Let's say, I am getting the results from database something like as:
var results []<someClass>
collection.C(results).Find(bson.M{"<someid>":<id_val>}).All(&results)
Now, I have my database objects/results available in slice results
. How can I sort the slice results
in reverse order on a column called time?
答案1
得分: 4
最简单的方法是让MongoDB对记录进行排序:
var results []YourType
err := sess.DB("").C("collname").Find(bson.M{"someid": "someidval"}).
Sort("-timefield").All(&results)
如果由于某种原因你不能或不想这样做,你可以使用sort
包。你需要实现sort.Interface
接口。
例如:
type YourType struct {
SomeId string
Timestamp time.Time
}
type ByTimestamp []YourType
func (a ByTimestamp) Len() int { return len(a) }
func (a ByTimestamp) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTimestamp) Less(i, j int) bool {
return a[i].Timestamp.After(a[j].Timestamp)
}
ByTimestamp
类型是YourType
的切片,并且它定义了一个逆时间戳顺序,因为Less()
方法使用Time.After()
来判断索引i
处的元素是否小于索引j
处的元素。
使用它(在Go Playground上尝试):
var results []YourType
// 在这里运行你的MongoDB查询
// 现在按照时间戳降序排序:
sort.Sort(ByTimestamp(results))
Less()
的另一种实现方式是使用Time.Before()
,但是将索引j
处的元素与索引i
处的元素进行比较:
func (a ByTimestamp) Less(i, j int) bool {
return a[j].Timestamp.Before(a[i].Timestamp)
}
在Go Playground上尝试这个变体。
英文:
Easiest would be to let MongoDB sort the records:
var results []YourType
err := sess.DB("").C("collname").Find(bson.M{"someid": "someidval"}).
Sort("-timefield").All(&results)
If for some reason you can't or don't want to do this, you may utilize the sort
package. You need to implement sort.Interface
.
For example:
type YourType struct {
SomeId string
Timestamp time.Time
}
type ByTimestamp []YourType
func (a ByTimestamp) Len() int { return len(a) }
func (a ByTimestamp) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTimestamp) Less(i, j int) bool {
return a[i].Timestamp.After(a[j].Timestamp)
}
This ByTimestamp
type is a slice of YourType
, and it defines a reverse timestamp order because the Less()
method uses Time.After()
to decide if element and index i
is less than element at index j
.
And using it (try it on the Go Playground):
var results []YourType
// Run your MongoDB query here
// Now sort it by Timestamp decreasing:
sort.Sort(ByTimestamp(results))
An alternative implementation for Less()
would be to use Time.Before()
, but compare element at index j
to index i
:
func (a ByTimestamp) Less(i, j int) bool {
return a[j].Timestamp.Before(a[i].Timestamp)
}
Try this variant on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论