Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list of objects to Collections.map

Tags:

f#

Given a list kinda like (simplified):

type foo(n:string,m:string,l:string) = 
    member f.name=n
    member f.val1=m
    member f.val2=l
let dates = [
    foo("a","aa","aaa")
    foo("b","bb","bbb")
]

How can a a immutable dictionary-type structure (eg, Map, IDictionary...any others?) of the form key:foo.name,value:foo be made?

My best guess was

let fooDict = for f in foo do yield f.name,f

But that for-comprehension syntax can only be used to make a list, array, or seq?

like image 839
Noel Avatar asked Mar 06 '13 21:03

Noel


People also ask

Can we convert list to Map in Java?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.

How do I get the field list of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.


1 Answers

To create an immutable dictionary (the interface is mutable, but will throw an exception if you try to modify it)

[ for f in dates -> f.name,f ] |> dict

or

dates |> Seq.map (fun f -> f.name, f) |> dict


To create an immutable Map:

[ for f in dates -> f.name,f ] |> Map.ofSeq

or

dates |> Seq.map (fun f -> f.name, f) |> Map.ofSeq
like image 166
Gustavo Guerra Avatar answered Sep 30 '22 15:09

Gustavo Guerra