Created
September 25, 2018 14:21
-
-
Save csharpforevermore/8a4d0885f7cf883891bd416804e38444 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
namespace Next.Whs.DDespatch.Framework.Models.Mapping.Custom | |
{ | |
public class ExampleImplementationClass | |
{ | |
public ExampleImplementationClass() | |
{ | |
MapperBase<Entity, DTO> userMapper = new UserMapper(); | |
var users = new List<Entity>(); | |
List<DTO> userDtos = userMapper.Map(users, delegate (DTO u) | |
{ | |
//Update UserDto object here | |
u.UserAddress = ""; | |
}); | |
} | |
} | |
public class Entity | |
{ | |
public string Name { get; set; } | |
public string Address { get; set; } | |
} | |
public class DTO | |
{ | |
public string UserName { get; set; } | |
public string UserAddress { get; set; } | |
} | |
public abstract class MapperBase<TFirst, TSecond> | |
{ | |
public abstract TFirst Map(TSecond element); | |
public abstract TSecond Map(TFirst element); | |
public List<TFirst> Map(List<TSecond> elements, Action<TFirst> callback = null) | |
{ | |
var objectCollection = new List<TFirst>(); | |
if (elements != null) | |
{ | |
foreach (TSecond element in elements) | |
{ | |
TFirst newObject = Map(element); | |
if (newObject != null) | |
{ | |
callback?.Invoke(newObject); | |
objectCollection.Add(newObject); | |
} | |
} | |
} | |
return objectCollection; | |
} | |
public List<TSecond> Map(List<TFirst> elements, Action<TSecond> callback = null) | |
{ | |
var objectCollection = new List<TSecond>(); | |
if (elements != null) | |
{ | |
foreach (TFirst element in elements) | |
{ | |
TSecond newObject = Map(element); | |
if (newObject != null) | |
{ | |
callback?.Invoke(newObject); | |
objectCollection.Add(newObject); | |
} | |
} | |
} | |
return objectCollection; | |
} | |
} | |
public sealed class UserMapper : MapperBase<Entity, DTO> | |
{ | |
public override Entity Map(DTO element) | |
{ | |
return new Entity | |
{ | |
Name = element.UserName, | |
Address = element.UserAddress | |
}; | |
} | |
public override DTO Map(Entity element) | |
{ | |
return new DTO | |
{ | |
UserName = element.Name, | |
UserAddress = element.Address | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment