Last active
December 22, 2015 10:09
-
-
Save gabrieljoelc/6456654 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Dynamic; | |
namespace Core.Utils | |
{ | |
public static class ReflectionExtensions | |
{ | |
public static ExpandoObject ToExpando(this object values) | |
{ | |
if (values == null) return null; | |
IDictionary<string, object> anonymousDictionary = new Dictionary<string, object>(); | |
anonymousDictionary.AddValues(anonymousDictionary); | |
IDictionary<string, object> expando = new ExpandoObject(); | |
foreach (var item in anonymousDictionary) | |
expando.Add(item); | |
return (ExpandoObject)expando; | |
} | |
public static void AddValues(this IDictionary<string, object> dict, object values) | |
{ | |
if (dict == null || values == null) return; | |
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values)) | |
{ | |
object obj2 = descriptor.GetValue(values); | |
dict.Add(descriptor.Name, obj2); | |
} | |
} | |
public static IDictionary<string, object> ToDictionary(this object withProperties) | |
{ | |
IDictionary<string, object> dict = new Dictionary<string, object>(); | |
if (withProperties == null) | |
{ | |
return dict; | |
} | |
var properties = TypeDescriptor.GetProperties(withProperties); | |
foreach (PropertyDescriptor property in properties) | |
{ | |
dict.Add(property.Name, property.GetValue(withProperties)); | |
} | |
return dict; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment