Grouping a list into a list of lists in F #

Ok, so I got lost on this. I have a list of objects. Each object is not a unique identifier in it. I want to group this identifier, but for life I cannot figure out how to do this.

This is what I have

type fooObject = {
     Id : int
     Info : string
}

let fooObjects: fooObject list

The data may 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

Thus, the end result will look like this:

[ [{ Id = 1 ; Data = "foo" } ; { Id = 1 ; Data = "also foo" } ] ; [{ Id = 2 ; Data = "Not foo" }]]
+4
source share
1 answer

Use List.groupBy:

let groupById fooObjects =
    List.groupBy (fun foo -> foo.Id) fooObjects
        |> List.map snd
+7
source

Source: https://habr.com/ru/post/1684488/


All Articles