Skip to content

Instantly share code, notes, and snippets.

@crosbymichael
Created January 27, 2012 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crosbymichael/1686407 to your computer and use it in GitHub Desktop.
Save crosbymichael/1686407 to your computer and use it in GitHub Desktop.
ObjectMapper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace MVVM_Async.Helpers
{
public static class ObjectMapper
{
public static T MapObjectToType<T>(object fromObject) {
var output = Activator.CreateInstance<T>();
Type outputType = typeof(T);
List<PropertyInfo> fromProperties = fromObject.GetType().GetProperties().ToList<PropertyInfo>();
List<PropertyInfo> toProperties = outputType.GetProperties().ToList<PropertyInfo>();
var matchingProperties = from f in fromProperties
join t in toProperties
on f.Name equals t.Name
select new { Name = f.Name, Value = f.GetValue(fromObject, null) };
foreach (var match in matchingProperties) {
outputType.GetProperty(match.Name).SetValue(output, match.Value, null);
}
return output;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment