Geeks With Blogs
.Nettuce Code Salad
    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;
        }
    }
Posted on Saturday, June 2, 2012 8:10 PM | Back to top


Comments on this post: Convert Dynamic to Type and convert Type to Dynamic

# re: Convert Dynamic to Type and convert Type to Dynamic
Requesting Gravatar...
I've got almost the same code, but I have a private static Dictionary<Type, Expression> to hold the prebuilt expression, sadly it will be angry with a different set of input keys... maybe another key-type for the expression cache would be nice.
Left by Marc Brooks on Oct 10, 2012 9:32 PM

Your comment:
 (will show your gravatar)


Copyright © Jon Canning | Powered by: GeeksWithBlogs.net