Skip to content

Instantly share code, notes, and snippets.

@sondreb
Created April 14, 2015 14:14
Show Gist options
  • Save sondreb/aa927c271efae76c3c59 to your computer and use it in GitHub Desktop.
Save sondreb/aa927c271efae76c3c59 to your computer and use it in GitHub Desktop.
DictionaryToObject
namespace Utils
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class DictionaryExtensions
{
public static T DictionaryToObject<T>(this IDictionary<string, string> dict) where T : new()
{
var t = new T();
PropertyInfo[] properties = t.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
continue;
KeyValuePair<string, string> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
// Find which property type (int, string, double? etc) the CURRENT property is...
Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
// Fix nullables...
Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
// ...and change the type
object newA = Convert.ChangeType(item.Value, newT);
t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
}
return t;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment