I have two list of variable length. I want to map destination list partially. Destination list should be mapped only till the length of source list.
public class Child
{
public Child(int id,string name, int age)
{
Id = id;
Name = name;
Age = age;
}
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class ChildDTO
{
public ChildDTO(int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
}
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
var listChild = new List<Child>();
listChild.Add(new Child(1,"Jhon",30)) ;
var listChildDTO = new List<ChildDTO>();
listChildDTO.Add(new ChildDTO(2, "Mike", 33));
listChildDTO.Add(new ChildDTO(3, "Roy", 32));
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Child, ChildDTO>();
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
var dest = mapper.Map<List<Child>, List<ChildDTO>>(listChild,listChildDTO);
I want result like :-
2, "Mike", 33;
3, "Roy", 32;
CodePudding user response:
Your 'I want result like' section just shows ListChildDTO unaltered, are you sure you don't mean you mean
I want result like :-
1, "Jhon", 30;
3, "Roy", 32;
If so, and if I'm understanding how the automapper works, why not just provide it with an altered list using linq?
var dest = mapper.Map<List<Child>, List<ChildDTO>>(listChild, listChildDTO.Take(listChild.Count).ToList());
Above is assuming .Map alters the items directly. If I'm wrong and it leaves each object unaltered and returns an altered list, you can just merge it with the original list after the fact
dest.AddRange(listChildDTO.Skip(listChild.Count));
I've made a lot of assumptions about AutoMapper here, but using Skip, Take, and AddRange in some combination should make what you're after possible