fx-sharp  0.1
A collection of functional extensions for C#.
 All Classes Namespaces Files Functions Variables Enumerator
DictionaryExtensions.cs
Go to the documentation of this file.
1 using System.Collections.Generic;
2 using FxSharp.Utils;
3 using JetBrains.Annotations;
4 
5 namespace FxSharp.Extensions
6 {
7  /// <summary>
8  /// Extension methods for dictionaries.
9  /// </summary>
10  public static class DictionaryExtensions
11  {
12  /// <summary>
13  /// Get a value from a dictionary.
14  /// Unlike the normal dictionary method, it returns Maybe.Nothing if the key is not
15  /// present and wraps the value in Maybe.Just if a value for this key is present.
16  /// </summary>
17  /// <typeparam name="TKey">Dictionary key type.</typeparam>
18  /// <typeparam name="TValue">Dictionary value type.</typeparam>
19  /// <param name="dict">Dictionary to access.</param>
20  /// <param name="key">Key to look up.</param>
21  /// <returns>
22  /// Maybe.Just(T) when key is present, Maybe.Nothing(T) when key is not present.
23  /// </returns>
24  public static Maybe<TValue> GetMaybe<TKey, TValue>(
25  [NotNull] this IDictionary<TKey, TValue> dict,
26  [NotNull] TKey key)
27  {
28  Ensure.NotNull(dict, "dict");
29  Ensure.NotNull(key, "key");
30 
31  return dict.ContainsKey(key) ? Maybe.Just(dict[key]) : Maybe.Nothing<TValue>();
32  }
33  }
34 }