将切片调整为新顺序

时间:2019-05-03 09:14:59

标签: go

我有类型...

type MyType struct {
    Job       string `json:"Job"`
    Cost      string `json:"Cost"`

}

这种类型的切片...

var records []MyType

它的填充如下...

records = append(records, MyType{Job: 100, Cost:234},)
records = append(records, MyType{Job: 101, Cost:4000},)
records = append(records, MyType{Job: 102, Cost:700},)

我想按成本降序对“行”进行排序,以便...

records [0]。职位等于101 条记录[0]。费用等于4000

records [1] .Job等于102 条记录[1]。成本等于700

records [2]。职位等于100 条记录[2]。费用等于234

在C#中,我通常会使用linq,但是我是新手,因此不确定如何解决此问题...

1 个答案:

答案 0 :(得分:2)

首先json类型无效。费用应为int类型

尝试此代码

import (
    "fmt"
    "sort"
)

type Records []MyType

type MyType struct {
    Job  int `json:"Job"`
    Cost int `json:"Cost"`
}

func (r Records) Len() int           { return len(r) }
func (r Records) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
func (r Records) Less(i, j int) bool { return r[i].Cost > r[j].Cost }

func main() {

    records := make(Records, 0, 1000)
    records = append(records, MyType{Job: 100, Cost: 234})
    records = append(records, MyType{Job: 101, Cost: 4000})
    records = append(records, MyType{Job: 102, Cost: 700})

    sort.Sort(records)
    fmt.Println(records)
}

或没有自定义切片

type MyType struct {
    Job  int `json:"Job"`
    Cost int `json:"Cost"`
}

func main() {

    records := make([]MyType, 0, 1000)
    records = append(records, MyType{Job: 100, Cost: 234})
    records = append(records, MyType{Job: 101, Cost: 4000})
    records = append(records, MyType{Job: 102, Cost: 700})

    sort.Slice(records, func(i, j int) bool {
        return records[i].Cost > records[j].Cost
    })
    fmt.Println(records)
}

输出

[{101 4000} {102 700} {100 234}]

ref https://golang.org/pkg/sort/#Slice