Created
February 24, 2013 06:19
-
-
Save taogawa/5022854 to your computer and use it in GitHub Desktop.
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 FastMember; | |
namespace Mapper | |
{ | |
public class Mapper | |
{ | |
public static IEnumerable<TDest> MapTo<TSrc, TDest>(IEnumerable<TSrc> src) | |
{ | |
var srcType = TypeAccessor.Create(typeof(TSrc)); | |
var destType = TypeAccessor.Create(typeof(TDest)); | |
var srcProps = srcType.GetMembers(); | |
var destProps = destType.GetMembers(); | |
var matchedProps = (from s in srcProps | |
from d in destProps | |
where s.Name == d.Name | |
where s.Type == d.Type | |
select new { Source = s, Dest = d }) | |
.ToDictionary(x => x.Source, x => x.Dest); | |
foreach (var s in src) | |
{ | |
var dest = destType.CreateNew(); | |
foreach (var prop in matchedProps) | |
{ | |
destType[dest, prop.Value.Name] = srcType[s, prop.Key.Name]; | |
} | |
yield return (TDest)dest; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment