Created
January 27, 2012 01:46
-
-
Save crosbymichael/1686407 to your computer and use it in GitHub Desktop.
ObjectMapper
This file contains 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; | |
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