May 27 2024
public class Mapper<TSource, TDestination>
{
public TDestination Map(TSource source)
{
var destination = Activator.CreateInstance<TDestination>();
foreach (var sourceProperty in typeof(TSource).GetProperties())
{
var destinationProperty = typeof(TDestination).GetProperty(sourceProperty.Name);
if (destinationProperty != null)
{
destinationProperty.SetValue(destination, sourceProperty.GetValue(source));
}
}
return destination;
}
public List<TDestination> Map(List<TSource> sourceList)
{
return sourceList.Select(source => Map(source)).ToList();
}
}
var mapper = new Mapper<User, UserModel>();
List<UserModel> userModels = mapper.Map(users);
public class UserMapperService
{
public User MapToUser(UserModel userModel)
{
return new User
{
Id = userModel.Id,
Address = userModel.Address,
City = userModel.City,
Email = userModel.Email,
FirstName = userModel.FirstName,
LastName = userModel.LastName,
Password = userModel.Password,
PostalCode = userModel.PostalCode,
Region = userModel.Region
};
}
public UserModel MapToUserModel(User user)
{
return new UserModel
{
Id = user.Id,
Address = user.Address,
City = user.City,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
Password = user.Password,
PostalCode = user.PostalCode,
Region = user.Region
};
}
}
UserModel userModel = _userMapperService.MapToUserModel(user);
List<User> users = _userRepository.GetUsers();
List<UserModel> userModels = users.Select(x => new UserModel
{
Address = x.Address,
City = x.City,
Email = x.City,
FirstName = x.FirstName,
Id = x.Id,
LastName = x.LastName,
Password = x.Password,
PostalCode = x.PostalCode,
Region = x.Region
}).ToList();
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.