Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 65 lines (52 sloc) 2.086 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
using System;
using System.Collections.Generic;
using System.Linq;

namespace FubuCore
{
    public static class DictionaryExtensions
    {
        public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
        {
            return dictionary.Get(key, default(TValue));
        }

        public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
        {
            if (dictionary.ContainsKey(key)) return dictionary[key];
            return defaultValue;
        }

        /// <summary>
        /// This is a big THANK YOU to the BCL for not hooking a brotha' up
        /// This add will tell WHAT KEY you added twice.
        /// </summary>
        public static void SmartAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
        {
            try
            {
                dictionary.Add(key, value);
            }
            catch (ArgumentException e)
            {
                throw new ArgumentException("The key '{0}' already exists.".ToFormat(key), e);
            }
        }



        public static T Get<T>(this IDictionary<string, object> dictionary, string key)
        {
            if (key.Contains("/"))
            {
                var parts = key.Split('/');

                var nextKey = parts.Skip(1).Join("/");

                var child = dictionary.Get<IDictionary<string, object>>(parts.First());


                return child.Get<T>(nextKey);
            }

            return (T)dictionary[key];
        }

        public static IDictionary<string, object> Child(this IDictionary<string, object> dictionary, string key)
        {
            return dictionary[key].As<IDictionary<string, object>>();
        }

        public static IEnumerable<IDictionary<string, object>> Children(this IDictionary<string, object> dictionary, string key)
        {
            return dictionary.Get<IEnumerable<IDictionary<string, object>>>(key);
        }
    }
}
Something went wrong with that request. Please try again.