75

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

Hamed Moghadasi
  • 1,523
  • 2
  • 16
  • 34
TheBoubou
  • 19,487
  • 54
  • 148
  • 236

3 Answers3

139

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.

Diego Rafael Souza
  • 5,241
  • 3
  • 23
  • 62
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 4
    What's interesting to note here, is that the source template can be the most generic type, like `PersonView[]` and the output can be of any other supported type such as `IEnumerable, ICollection, IList, etc` – Alex Feb 24 '12 at 15:37
20

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);
Ogglas
  • 62,132
  • 37
  • 328
  • 418
2

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);
 }
Antonio Correia
  • 1,093
  • 1
  • 15
  • 22