Skip to content

Instantly share code, notes, and snippets.

@haukurk
Created November 15, 2016 15:10
Show Gist options
  • Save haukurk/7e730ef734c1f4007fe5bee45cb39d58 to your computer and use it in GitHub Desktop.
Save haukurk/7e730ef734c1f4007fe5bee45cb39d58 to your computer and use it in GitHub Desktop.
DTO Extensions
/// <summary>
/// Extension methods for mapping entities to DTOs
/// </summary>
public static class DTOExtensions
{
/// <summary>
/// Extension method for IEnumerable to map them to DTO of type T
/// </summary>
/// <typeparam name="T">DTO type</typeparam>
/// <param name="obj">Collection of entities</param>
/// <returns>Collection of DTO</returns>
public static IEnumerable<T> ToDTO<T>(this IEnumerable<object> obj) where T : class, new()
{
if (obj == null) return null;
return obj.ToList().Select(x => new T().InjectFrom(x)).Cast<T>();
}
public static T ToDTO<T>(this object obj) where T : class, new()
{
if (obj == null) return null;
return new T().InjectFrom(obj) as T;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment