tags:

views:

153

answers:

3

I'm wondering if there is a better way to do the following,

    IList<RoleViewModel> ReturnViewModel = new List<RoleViewModel>();

    IList<Role> AllRoles = PermServ.GetAllRoles();

    foreach (var CurRole in AllRoles)
    {
        ReturnViewModel.Add(new RoleViewModel(CurRole));
    }

Its pretty simple code simply taking the Data Object and converting it into a ViewModel. I was wondering if there was a way to do this better? - Maybe with Linq?

+6  A: 
var returnViewModel  = (from n in PermServ.GetAllRoles()
                       select new RoleViewModel(n)).ToList();
Hath
Should be Select new RoleViewModel(n)).ToList(); No?
Michael Gattuso
yep - just saw it.
Hath
+7  A: 

From the top of my head (not by dev machine).

IList<RoleViewModel> returnViewModel = PermServ.GetAllRoles()
                                        .Select(x => new RoleViewModel(x))
                                        .ToList();
Michael Gattuso
'IList<Role> AllRoles =' should this be 'IList<RoleViewModel> AllRoles ='
Hath
People in glass houses ... right. :-)
Michael Gattuso
A: 

Another option is to use AutoMapper handle your conversions.

Mapper.CreateMap<Role, RoleModel>();
IList<RoleViewModel> returnViewModel = 
   Mapper.Map<IList<Role>, IList<RoleViewModel>>(PermServ.GetAllRoles());
Even Mien