根据具有map [string]接口项的值对切片进行排序

时间:2018-04-18 09:01:26

标签: go

编辑后

实际情况与样本数据略有不同。

我有一个表,其中包含与我在应用程序中使用的用户界面相关的所有字段和属性。我需要一个由listorder排序的简单切片,只有这样的字段名称列表。

colons=[]string{'id', 'name', 'population', 'phonecode'}

但是数据源是一个切片,包含来自像这样的SQL查询的map[string]interface{}

select fieldname, 
       label, 
       listorder 
  from tablefields 
 where tablename="city"  
 order by fieldname


fields := []map[string]interface{} {
  {"fieldname": "id",         "label": "Id No",      "listorder": "01"},
  {"fieldname": "name",  ,    "label": "City Name",  "listorder": "03"},
  {"fieldname": "phonecode",  "label": "Phone Code", "listorder": "02"},
  {"fieldname": "population", "label": "Population", "listorder": "04"},
}

1 个答案:

答案 0 :(得分:1)

我在评论中得到彼得的提示后解决了这个问题。

解决方案:

package main

import (
    "fmt"
    "sort"
)

type ByListOrder []map[string]interface{}

func (a ByListOrder) Len() int           { return len(a) }
func (a ByListOrder) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByListOrder) Less(i, j int) bool { return a[i]["listorder"].(string) < a[j]["listorder"].(string) }


func main() {
    fields := []map[string]interface{} {
          {"fieldname": "id",         "label": "Id No",      "listorder": "01"},
          {"fieldname": "name",       "label": "City Name",  "listorder": "03"},
          {"fieldname": "phonecode",  "label": "Phone Code", "listorder": "02"},
          {"fieldname": "population", "label": "Population", "listorder": "04"},
    }      

    fmt.Println(fields)
    sort.Sort(ByListOrder(fields))
    fmt.Println(fields)

}

https://play.golang.org/p/7AVfIt_Zihx