struct/results的逆时间顺序

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

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 []&lt;someClass&gt;
collection.C(results).Find(bson.M{&quot;&lt;someid&gt;&quot;:&lt;id_val&gt;}).All(&amp;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(&quot;&quot;).C(&quot;collname&quot;).Find(bson.M{&quot;someid&quot;: &quot;someidval&quot;}).
    Sort(&quot;-timefield&quot;).All(&amp;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.

huangapple
  • 本文由 发表于 2016年11月28日 18:52:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/40842503.html
匿名

发表评论

匿名网友

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

确定