Created
April 14, 2015 14:14
-
-
Save sondreb/aa927c271efae76c3c59 to your computer and use it in GitHub Desktop.
DictionaryToObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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