convert an object list with list to a single list

89 Views Asked by At

I have an object list, containing objects like:

Userobject{
    username
    userage
...
    userrolesList // is a List<userrole>
}

userrole{
    rolid
    rolname
    rolcommission
}

userrolesList can have one or more userroleobjects.

I need to send this list to another system, but the other system only accepts a list of objects like:

Userobject{
    username
    userage
...
    userroleobject // is a userrole object
}

userrole{
    rolid
    rolname
    rolcommission
}

In this case if one user have 10 roles I need to send 10 different objects to the other system. Any suggestion how I can make this easily and not affect the performance?

2

There are 2 best solutions below

0
Will Ray On

This is pretty easy with LINQ query syntax:

var results = from user in userObjects
              from role in user.UserRolesList
              select new OtherSystemUserObject
              {
                  UserAge = user.UserAge,
                  UserName = user.UserName,
                  UserRole = role
                  // other mapping stuff...
              };
0
Javier Escobar Espinoza On

What you are trying to do is not very logical, my friend. However, what comes to my mind is: You can create a class with the class model you need to send an then iterate through the userrolelist casting each element to a single userrole object. Like this:

for(int i = 0; i < userobject.userroleslist.Count ; i++)
{
    var userrole = userobject.userroleslist[i];
    //  Map your object with this userrole variable
}