Fill a list of objects (with Linq?)

I am 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 fairly simple code just takes a data object and converts it to a ViewModel. I was wondering if there is a way to make this better? “Maybe with Link?”

+4
source share
3 answers

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

 IList<RoleViewModel> returnViewModel = PermServ.GetAllRoles() .Select(x => new RoleViewModel(x)) .ToList(); 
+7
source
 var returnViewModel = (from n in PermServ.GetAllRoles() select new RoleViewModel(n)).ToList(); 
+6
source

Another option is to use AutoMapper to process your conversions.

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

All Articles