douzhong2954 2019-05-03 09:14
浏览 87
已采纳

将切片调整为新顺序

I have a type...

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

}

A slice of this type...

var records []MyType

It is populated as follows...

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

I would like to sort the 'rows' by cost descending so...

records[0].Job would equal 101 records[0].Cost would equal 4000

records[1].Job would equal 102 records[1].Cost would equal 700

records[2].Job would equal 100 records[2].Cost would equal 234

In c# i would normally use linq, but I am new to go and not sure how to go about this...

  • 写回答

1条回答 默认 最新

  • dongzhu3548 2019-05-03 09:21
    关注

    first of all json type is invalid. Cost should be int type

    try this code

    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)
    }
    

    or without custom slices

    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)
    }
    

    output

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法