如何使用多个排序参数对结构进行排序?

我有一个成员数组/切片:


type Member struct {

    Id int

    LastName string

    FirstName string

}


var members []Member

我的问题是如何对它们进行排序LastName,然后由FirstName.


猛跑小猪
浏览 174回答 3
3回答

GCT1015

使用sort.Slice(自 Go 1.8 起可用)或sort.Sort函数对值的切片进行排序。通过这两个函数,应用程序提供了一个函数来测试一个切片元素是否小于另一个切片元素。要先按姓氏再按名字排序,请先比较姓氏然后是名字:if members[i].LastName < members[j].LastName {&nbsp; &nbsp; return true}if members[i].LastName > members[j].LastName {&nbsp; &nbsp; return false}return members[i].FirstName < members[j].FirstName使用带有 sort.Slice 的匿名函数指定 less 函数:var members []Membersort.Slice(members, func(i, j int) bool {&nbsp; &nbsp; if members[i].LastName < members[j].LastName {&nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; }&nbsp; &nbsp; if members[i].LastName > members[j].LastName {&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }&nbsp; &nbsp; return members[i].FirstName < members[j].FirstName})less 函数是通过带有 sort.Sort 函数的接口指定的:type byLastFirst []Memberfunc (members byLastFirst) Len() int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ return len(members) }func (members byLastFirst) Swap(i, j int)&nbsp; &nbsp; &nbsp; { members[i], members[j] = members[j], members[i] }func (members byLastFirst) Less(i, j int) bool {&nbsp;&nbsp; &nbsp; if members[i].LastName < members[j].LastName {&nbsp; &nbsp; &nbsp; &nbsp;return true&nbsp; &nbsp; }&nbsp; &nbsp; if members[i].LastName > members[j].LastName {&nbsp; &nbsp; &nbsp; &nbsp;return false&nbsp; &nbsp; }&nbsp; &nbsp; return members[i].FirstName < members[j].FirstName}sort.Sort(byLastFirst(members))除非性能分析表明排序是一个热点,否则请使用对您的应用程序最方便的函数。

江户川乱折腾

sort.Slice像这样使用较新的函数:sort.Slice(members, func(i, j int) bool {&nbsp; &nbsp; switch strings.Compare(members[i].FirstName, members[j].FirstName) {&nbsp; &nbsp; case -1:&nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; case 1:&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }&nbsp; &nbsp; return members[i].LastName > members[j].LastName})或类似的东西。

12345678_0001

另一种模式,我觉得它稍微干净一点:if members[i].LastName != members[j].LastName {&nbsp; &nbsp; return members[i].LastName < members[j].LastName}return members[i].FirstName < members[j].FirstName
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go