dqz84361326
2018-07-26 16:00
采纳率: 0%
浏览 1.2k
已采纳

在golang中循环遍历数组对象和分组的最佳方法

I have a list of Books (BookId) and each book is associated to a Book collection (CollectionId).

I am trying to figure out the best way to group the results by Collection, so all the books that belong to a collection are listed under it and I can build the results in the following way:

Book A,D,G belong to Collection 1. Book B,C,E belong to Collection 2.

I have the books in a list/array that I need to loop through and look up the collectionID they belong to and them need to store the new lists as seen below:

CollectionID 1:

- Book A, Book D, Book G

CollectionID 2:

- Book B, Book C, Book E

CollectionID 3:

- Book F

图片转代码服务由CSDN问答提供 功能建议

我有一个图书清单(BookId),每本书与一个图书收藏集(CollectionId)相关联。

我正在尝试找出按“收藏”对结果进行分组的最佳方法,因此,在该收藏下列出了属于该收藏的所有书籍,我可以通过以下方式构建结果 :

书籍A,D,G属于集合1。 书籍B,C,E属于集合2。

我有书籍 在需要遍历的列表/数组中,查找它们所属的collectionID,并需要存储新列表,如下所示:

CollectionID 1: \ n

 -图书A,图书D,图书G 
   
 
 

CollectionID 2:

 < 代码>-图书B,图书C,图书E 
   
 
 

CollectionID 3:

 -图书F 
    
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongque1462 2018-07-26 16:35
    已采纳

    You can use a map to store a slice of books per collection ID.

    type Book struct {
        Title        string
        Author       string
        CollectionID int
    }
    
    func main() {
        books := GetBooks()
        collections := make(map[int][]Book)
        for _, b := range books {
            collections[b.CollectionID] = append(collections[b.CollectionID], b)
        }
        ...
    }
    
    点赞 打赏 评论
  • douzhi0107 2018-07-26 16:35

    First, you design your database. For example,

    package main
    
    type CollectionId string
    
    type Collection struct {
        Id   CollectionId
        Name string
    }
    
    type BookId string
    
    type Book struct {
        Id         BookId
        Name       string
        Collection CollectionId
    }
    
    type Books map[BookId]Book
    
    type Collections map[CollectionId][]BookId
    
    func main() {}
    
    点赞 打赏 评论

相关推荐 更多相似问题