let claimsList =
[ {|cType = "uid"; cValue="1"|};
{|cType = "name"; cValue="N1"|};
{|cType = "sid"; cValue="sid1"|};
{|cType = "email"; cValue="[email protected]"|};
{|cType = "company"; cValue="Company1"|}]
let email = claimsList
|> List.tryFind(fun c -> c.cType = "email")
|> Option.map(fun c -> c.cValue)
let company = claimsList
|> List.tryFind(fun c -> c.cType = "company")
|> Option.map(fun c -> c.cValue)
let userId = claimsList
|> List.tryFind(fun c -> c.cType = "userId")
|> Option.map(fun c -> c.cValue)
(email, userId, company)
I don't like the fact that I am iterating the list multiple times and looks complicated. Is there a way to simplify this?
The map() function iterates over all elements in a list (or a tuple), applies a function to each, and returns a new iterator of the new elements. In this syntax, fn is the name of the function that will call on each element of the list. In fact, you can pass any iterable to the map() function, not just a list or tuple.
Use a map when you want your data structure to represent a mapping for keys to values. Use a list when you want your data to be stored in an arbitrary, ordered format.
The ArrayList has O(n) performance for every search, so for n searches its performance is O(n^2). The HashMap has O(1) performance for every search (on average), so for n searches its performance will be O(n). While the HashMap will be slower at first and take more memory, it will be faster for large values of n.
If you need to look up claims multiple times, and provided they all have different cType
s, you could convert the list to a map and then lookup in it:
let map = claimsList |> List.map (fun r -> r.cType, r.cValue) |> Map.ofList
let email = map.["email"]
let company = map.["company"]
let userId = map.["uid"]
Note that indexing like map.["email"]
will crash at runtime if the key is not present in the map. This is fine if missing keys "shouldn't normally happen", but if you want to handle this case gracefully, use Map.tryFind
instead, which will return you an option
:
let email = map |> Map.tryFind "email"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With