Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a list of Objects (With Linq?)

Tags:

c#

asp.net

linq

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?

like image 485
LiamB Avatar asked Dec 13 '22 01:12

LiamB


1 Answers

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

IList<RoleViewModel> returnViewModel = PermServ.GetAllRoles()
                                        .Select(x => new RoleViewModel(x))
                                        .ToList();
like image 123
Michael Gattuso Avatar answered Dec 31 '22 14:12

Michael Gattuso