Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping a list into a list of lists in F#

Tags:

f#

Okay so I'm lost on this one. I have a list of objects. Each object as a non-unique ID in it. I want to group on this ID but for the life of me I can't figure out how to do this.

This is what I have

type fooObject = {
     Id : int
     Info : string
}

let fooObjects: fooObject list

The data might look something like this

[ { Id = 1 ; Data = "foo" } ; { Id = 1 ; Data = "also foo" } ; { Id = 2 ; Data = "Not foo" } ]

I would like something like

let fooObjectsGroupedById : fooObject list list

So the final result would look like this

[ [{ Id = 1 ; Data = "foo" } ; { Id = 1 ; Data = "also foo" } ] ; [{ Id = 2 ; Data = "Not foo" }]]
like image 698
Anthony Russell Avatar asked Mar 08 '23 05:03

Anthony Russell


1 Answers

Use List.groupBy:

let groupById fooObjects =
    List.groupBy (fun foo -> foo.Id) fooObjects
        |> List.map snd
like image 184
Chad Gilbert Avatar answered Mar 15 '23 16:03

Chad Gilbert