Skip to content

Instantly share code, notes, and snippets.

@taogawa
Created February 24, 2013 06:19
Show Gist options
  • Save taogawa/5022854 to your computer and use it in GitHub Desktop.
Save taogawa/5022854 to your computer and use it in GitHub Desktop.
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