按切片字段排序

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

Sorting by slice fields

问题

我有以下的结构体:

type Parent struct {
    id       string
    children []Child
}

type Child struct {
    id string
}

我创建了一个包含以下数值的 Parents 切片:

parents := make([]Parent, 0)

p1 := Parent {
    "3",
    []Child {
        {"2"},
        {"3"},
        {"1"},
    },
}

p2 := Parent {
    "1",
    []Child {
        {"8"},
        {"9"},
        {"7"},
    },
}

p3 := Parent {
    "2",
    []Child {
        {"5"},
        {"6"},
        {"4"},
    },
}

parents = append(parents, p1, p2, p3)

我想按照以下顺序对 parents 切片进行排序:

  1. 首先,按照 Parent.id 对所有的 Parents 进行排序。

  2. 接下来,按照每个 Parentchildren 切片中的 Child.id 进行排序。

期望的结果类似于:

[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]

在 Go 中有没有一种方法可以实现这个排序?

英文:

I have the following Structs:

type Parent struct {
    id       string
    children []Child
}

type Child struct {
    id string
}

I have made a slice of Parents with the following values:

parents := make([]Parent, 0)

p1 := Parent {
    "3",
    []Child {
        {"2"},
        {"3"},
        {"1"},
    },
}

p2 := Parent {
    "1",
    []Child {
        {"8"},
        {"9"},
        {"7"},
    },
}

p3 := Parent {
    "2",
    []Child {
        {"5"},
        {"6"},
        {"4"},
    },
}             

parents = append(parents, p1, p2, p3)

I am trying to sort the "parents" slice in the following order:

1) First, sort all Parents by Parent.id

2) Next, sort each Parent's "children" slice by Child.id

The expected result is something like:

[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]

Is there a way to do this in Go?

答案1

得分: 5

我用以下代码使其工作:

// 按照 Id 对 parents 切片中的每个 Parent 进行排序
sort.Slice(parents, func(i, j int) bool {return parents[i].id < parents[j].id})

// 对于每个 Parent,按照 Id 对 children 切片中的每个 Child 进行排序
for _, parent := range parents {
sort.Slice(parent.children, func(i, j int) bool {return parent.children[i].id < parent.children[j].id})
}

特别感谢 @Volker 提到的 sort.Slice 函数!我之前不知道它的存在!

英文:

I got it to work using the following code:

// sort each Parent in the parents slice by Id
sort.Slice(parents, func(i, j int) bool {return parents[i].id &lt; parents[j].id})

// for each Parent, sort each Child in the children slice by Id
for _, parent := range parents {
	sort.Slice(parent.children, func(i, j int) bool {return parent.children[i].id &lt; parent.children[j].id})
}

Special thanks to @Volker for mentioning the sort.Slice function! I had no idea it existed!

huangapple
  • 本文由 发表于 2017年4月10日 14:19:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/43316154.html
匿名

发表评论

匿名网友

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

确定