开发者

Populate a list of Objects (With Linq?)

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

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

    IList<Role> AllRoles = PermSer开发者_开发问答v.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?


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

IList<RoleViewModel> returnViewModel = PermServ.GetAllRoles()
                                        .Select(x => new RoleViewModel(x))
                                        .ToList();


var returnViewModel  = (from n in PermServ.GetAllRoles()
                       select new RoleViewModel(n)).ToList();


Another option is to use AutoMapper handle your conversions.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜