Convert Dynamic to Type and convert Type to Dynamic

Posted by Jon Canning on Geeks with Blogs See other posts from Geeks with Blogs or by Jon Canning
Published on Sat, 02 Jun 2012 18:10:17 GMT Indexed on 2012/06/02 22:41 UTC
Read the original article Hit count: 457

Filed under:
    public static class DynamicExtensions
    {
        public static T FromDynamic<T>(this IDictionary<stringobject> dictionary)
        {
            var bindings = new List<MemberBinding>();
            foreach (var sourceProperty in typeof(T).GetProperties().Where(x => x.CanWrite))
            {
                var key = dictionary.Keys.SingleOrDefault(x => x.Equals(sourceProperty.Name, StringComparison.OrdinalIgnoreCase));
                if (string.IsNullOrEmpty(key)) continue;
                var propertyValue = dictionary[key];
                bindings.Add(Expression.Bind(sourceProperty, Expression.Constant(propertyValue)));
            }
            Expression memberInit = Expression.MemberInit(Expression.New(typeof(T)), bindings);
            return Expression.Lambda<Func<T>>(memberInit).Compile().Invoke();
        }
 
        public static dynamic ToDynamic<T>(this T obj)
        {
            IDictionary<stringobject> expando = new ExpandoObject();
 
            foreach (var propertyInfo in typeof(T).GetProperties())
            {
                var propertyExpression = Expression.Property(Expression.Constant(obj), propertyInfo);
                var currentValue = Expression.Lambda<Func<string>>(propertyExpression).Compile().Invoke();
                expando.Add(propertyInfo.Name.ToLower(), currentValue);
            }
            return expando as ExpandoObject;
        }
    }

© Geeks with Blogs or respective owner