ValidateAndConvertDictionaryData

 public static class DictionaryExtensions
    {
        public static T ValidateAndConvertDictionaryData<T>(this Dictionary<string, object> dictionary, string dictionaryKey)
        {
            if (dictionary != null && dictionary.ContainsKey(dictionaryKey))
            {
                object dictionaryValue;
                dictionary.TryGetValue(dictionaryKey, out dictionaryValue);

                if (dictionaryValue != null)
                {
                    return dictionaryValue.TryToCast<T>();
                }
            }

            return default(T);
        }

   public static T TryToCast<T>(this object value)
        {
            if (value is T)
            {
                return (T)value;
            }
            try
            {

                if (typeof(T).IsEnum)
                {
                    return (T)Enum.Parse(typeof(T), value.ToString());
                }

                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch (Exception)
            {
                return default(T);
            }

        }

    }
Example:
  Dictionary<string, object> dictionary = new Dictionary<string, object> {{"FOO", 1}};
  string foo = dictionary.ValidateAndConvertDictionaryData<string>("FOO");

Description

Dictionary Extension

Details

Double click on the code to select all.

 

;