- Is my code just adding 'noise'?
Is my code just adding 'noise'?
- Is the implementation code below sound?
Is the implementation code below sound?
public static TResult ToDto<TSource, TResult>(this TSource obj, params Expression<Func<TSource, dynamic>>[] items) where TSource : class { var eo = new ExpandoObject(); var props = eo as IDictionary<String, object>;
foreach (var item in items) { var member = item.Body as MemberExpression; var unary = item.Body as UnaryExpression; var body = member ?? (unary != null ? unary.Operand as MemberExpression : null); if (member != null && body.Member is PropertyInfo) { var property = body.Member as PropertyInfo; props[property.Name] = obj.GetType() .GetProperty(property.Name) .GetValue(obj, null); } else { var property = unary.Operand as MemberExpression; if (property != null) { props[property.Member.Name] = obj.GetType() .GetProperty(property.Member.Name) .GetValue(obj, null); } else { var compiled = item.Compile(); var output = (KeyValuePair<string, object>)compiled.Invoke(obj); props[output.Key] = obj.GetType() .GetProperty(output.Value.ToString()) .GetValue(obj, null); } } } TResult result = Activator.CreateInstance<TResult>(); foreach (var item in props) { result.GetType().GetProperty(item.Key).SetValue(result, item.Value, null); } return result; }}
public static T2 ToDto<T1,T2>(this T1 obj, params Expression<Func<T1, dynamic>>[] items) where T1 : class
{
var eo = new ExpandoObject();
var props = eo as IDictionary<String, object>;
foreach (var item in items)
{
var member = item.Body as MemberExpression;
var unary = item.Body as UnaryExpression;
var body = member ?? (unary != null ? unary.Operand as MemberExpression : null);
if (member != null && body.Member is PropertyInfo)
{
var property = body.Member as PropertyInfo;
if (property != null)
props[property.Name] = obj.GetType().GetProperty(property.Name).GetValue(obj, null);
}
else if (unary != null)
{
var ubody = (UnaryExpression)item.Body;
var property = ubody.Operand as MemberExpression;
if (property != null)
{
props[property.Member.Name] = obj.GetType()
.GetProperty(property.Member.Name)
.GetValue(obj, null);
}
else // full expression with number funcs
{
var compiled = item.Compile();
var result = (KeyValuePair<string, object>)compiled.Invoke(obj);
props[result.Key] = result.Value;
}
}
}
string json = JsonConvert.SerializeObject(eo); // need json.net
var anon = JsonConvert.DeserializeAnonymousType<object>(json, Activator.CreateInstance<T2>());
return ((JObject)anon).ToObject<T2>();
}