Automapper copy List to List

C#AutomapperAutomapper 2

C# Problem Overview


I have these classes:

public class Person {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;}
}

public class PersonView {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;}
}

I defined this:

Mapper.CreateMap<Person, PersonView>();
Mapper.CreateMap<PersonView, Person>()
	.ForMember(person => person.Id, opt => opt.Ignore());

That's work for this:

PersonView personView = Mapper.Map<Person, PersonView>(new Person());

I'd like to make the same but for List<Person> to List<PersonView> but I don't find the right syntax.

Thanks

C# Solutions


Solution 1 - C#

Once you've created the map (which you've already done, you don't need to repeat for Lists), it's as easy as:

List<PersonView> personViews = 
    Mapper.Map<List<Person>, List<PersonView>>(people);

You can read more in the AutoMapper documentation for Lists and Arrays.

Solution 2 - C#

For AutoMapper 6< it would be:

In StartUp:

Mapper.Initialize(cfg => {
    cfg.CreateMap<Person, PersonView>();
    ...
});

Then use it like this:

List<PersonView> personViews = Mapper.Map<List<PersonView>>(people);

Solution 3 - C#

You can also try like this:

var personViews = personsList.Select(x=>x.ToModel<PersonView>());

where

 public static T ToModel<T>(this Person entity)
 {
      Type typeParameterType = typeof(T);

      if(typeParameterType == typeof(PersonView))
      {
          Mapper.CreateMap<Person, PersonView>();
          return Mapper.Map<T>(entity);
      }

      return default(T);
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKris-IView Question on Stackoverflow
Solution 1 - C#Justin NiessnerView Answer on Stackoverflow
Solution 2 - C#OgglasView Answer on Stackoverflow
Solution 3 - C#Antonio CorreiaView Answer on Stackoverflow