Group and Sum slices

2,012 views
Skip to first unread message

Marcos Bortolussi

unread,
Oct 11, 2016, 5:53:12 PM10/11/16
to golang-nuts
Hi, I come from the .NET world where I had LINQ so i could do in memory queries like the one we usually see in SQL.

I have a slice of this structure I want to group by 8 fields, and then sum another integer field. Something like:

type Register struct {
id1 int
id2 int
id3 int
id4 int
id5 int
id6 int
id7 int
id8 int
money int
}


I thought in:
  1.  Creating an Equal function, to compare structures (those eight fields).
  2. Iterate over the collection I'm analyzing. 
    1. For each item check if it is already in the hash table.
    2. If it is there => I sum the field.
    3. If it is not => I add the new item to hash table.
Is there a better way or any beautiful, perforfomant and easy ready to use library?

Caleb Doxsey

unread,
Oct 11, 2016, 8:46:02 PM10/11/16
to golang-nuts
Go doesn't have LINQ, but it does have a database/sql package. If you're not afraid of using strings, probably the cleanest way to do this would be to use sqlite, an embedded database, that understands SQL and has support for in-memory tables. Here's a go binding:


And an example:


You can use the special string: :memory: for an in-memory table rather than one stored on disk.

If you're looking for something less generic, but still fairly clean, you can use a struct as a key in a hash table: https://play.golang.org/p/1CIpvWd0jZ

type Key struct {
id1, id2, id3 int // etc
}

type Record struct {
Key
money int
}

func main() {
records := []Record{
{Key{1, 2, 3}, 1000},
{Key{1, 2, 3}, 500},
{Key{1, 2, 3}, 100},
}

m := map[Key]int{}
for _, r := range records {
m[r.Key] += r.money
}

fmt.Println(m)
// map[{1 2 3}:1600]
}
Reply all
Reply to author
Forward
0 new messages