1 people like it.

tryGetDefault dictionary extension

Try get a value from a dictionary and return a default value when not found. I provided two version. Pick the one you like the most.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
module Dict = 
    open System.Collections.Generic
    let tryGetDefault_v1 (d:IDictionary<'k,'v>) (key:'k) (defaultValue:'v) =
        if d.ContainsKey(key) then
            d.[key]
        else
            defaultValue

    let tryGetDefault_v2 (d:IDictionary<'k,'v>) (key:'k) (defaultValue:'v) =
        let mutable value = defaultValue
        if d.TryGetValue(key, &value) then
            value
        else
            defaultValue
namespace System
namespace System.Collections
namespace System.Collections.Generic
val tryGetDefault_v1 : d:IDictionary<'k,'v> -> key:'k -> defaultValue:'v -> 'v

Full name: Script.Dict.tryGetDefault_v1
val d : IDictionary<'k,'v>
type IDictionary<'TKey,'TValue> =
  member Add : key:'TKey * value:'TValue -> unit
  member ContainsKey : key:'TKey -> bool
  member Item : 'TKey -> 'TValue with get, set
  member Keys : ICollection<'TKey>
  member Remove : key:'TKey -> bool
  member TryGetValue : key:'TKey * value:'TValue -> bool
  member Values : ICollection<'TValue>

Full name: System.Collections.Generic.IDictionary<_,_>
val key : 'k
val defaultValue : 'v
IDictionary.ContainsKey(key: 'k) : bool
val tryGetDefault_v2 : d:IDictionary<'k,'v> -> key:'k -> defaultValue:'v -> 'v

Full name: Script.Dict.tryGetDefault_v2
val mutable value : 'v
IDictionary.TryGetValue(key: 'k, value: byref<'v>) : bool
Raw view New version

More information

Link:http://fssnip.net/n7
Posted:3 years ago
Author:Samuel Bosch
Tags: dictionary