Search code examples
c#asp.netasp.net-mvcasp.net-coreviewmodel

Cannot cast IEnumerable<ViewmodelA> to IEnumerable<ViewmodelB>


I retrieve a list with the type of IEnumerable<ViewmodelA> and need to cast this list to IEnumerable<ViewmodelB>. There are same and different properties in each viewmodel and I just want to map the same properties (Name and Surnmame). Is it possible using boxing or AutoMapper? I tried boxing but it is not working :(

IEnumerable<ViewmodelB> newList;
newList = (IEnumerable<ViewmodelB>)demoService.GetList(); //returns IEnumerable<ViewmodelA>

ViewodelA:

public class ViewmodelA {

    public string Name { get; set; }

    public string Surname { get; set; }

    public string School { get; set; }

    public string Number { get; set; }
}

ViewodelB:

public class ViewmodelB {

    public string Name { get; set; }

    public string Surname { get; set; }

    public string Work { get; set; }

    public string Address { get; set; }
}

Solution

  • For something so trivial as this operation I think I would just:

    var modelbs = modelas.Select(
      a => new Viewmodelb(){
        Name = a.Name,
        Surname = a.Surname
      }
    );
    

    You could make both viewmodels inherit from a base that has the Name and Surname in it, though note that this wouldn't allow you to cast a modela into a modelb, you could only cast the modela into the base class.

    Or you could provide a constructor in modelb that takes a modela object and pulls just the name/surname out of it and use it like:

    var modelbs = modelas.Select(
      a => new Viewmodelb(a)
    );
    

    Your class ViewmodelB would look like:

    public class ViewmodelB {
    
        public string Name { get; set; }
    
        public string Surname { get; set; }
    
        public string Work { get; set; }
    
        public string Address { get; set; }
    
        public ViewmodelB(ViewmodelA x){
          Name = x.Name;
          Surname = x.Surname;
    
          //maybe initialize other properties here
        }
    }