ksg
ksg

Reputation: 4067

How to set properties of a list from another different list in C#

I have two lists named RoleModel and RoleViewModel.

public class RoleVM
{
    public string text { get; set; }
    public string icon { get; set; }
    public string node { get; set; }
}

public partial class Role
{
    public int Id { get; set; }
    public string RoleName { get; set; }
    public Nullable<int> ChildID { get; set; }
}

How can I assign the property of rolename (from rolemodel) to text(from rolevm)

public ActionResult getJsonTree()
{
    List<Role> _lstRole = _db.Roles.ToList();
    List<RoleVM> _lstViewRole = new List<RoleVM>();
    foreach(var _role in _lstRole)
    {
        if (_role.ChildID == null)
        {
            _lstViewRole.Add(_role);//Adds the role model to rolevm class
        }                
    }            
    return Json(_lstViewRole, JsonRequestBehavior.AllowGet);
}

Upvotes: 0

Views: 1651

Answers (1)

fubo
fubo

Reputation: 45987

how about

List<RoleVM> _lstViewRole = _db.Roles.Where(x => x.Id == null).Select(x => new RoleVM() { text = x.RoleName }).ToList();
  • select all items where Id == null
  • create for each Role object a new RoleVM object and Role.RoleName goes to RoleVM.text

Upvotes: 3

Related Questions