Toni Toni - 3 years ago 62
C# Question

<Closed> how I can access the value of the properties in the object stored in objects

I have class Role:

class Role
{
public Role(Type1 parameter1, Type2 parameter2, Type3 parameter3)
{
}

}


Type1, Type2, Type3 are other classes. I am creating new object of type Role

Role role1 = new Role(parameter1, parameter2, parameter3);


And Adding it to a list

List<Role> listRoles = new List<Role>();
listRoles.Add(role1);


Now I need to fill an excel file with the items of this list, but how I can take the data from my objects in the list.

For an example, the first cell must be filled with role1.Type1.Name, how I can access the value of the properties in the object

Answer Source

You can just iterate the list and get the needed values. in this example I'm storing the values in strings, but you can do whatever is needed (e.g. directly write them into the Excel sheet):

foreach(Role role in listRoles)
{
    string col1 = role.Type1.Name;
    string col2 = role.Type2.Name;
    // and so on
} 

I assume, that your Role class looks something like this:

class Role
{
    public Type1 Type1 { get; set; }
    public Type2 Type2 { get; set; }
    public Type3 Type3 { get; set; }

    public Role(Type1 parameter1, Type2 parameter2, Type3 parameter3)
    { 
        this.Type1 = parameter1;
        this.Type2 = parameter2;
        this.Type3 = parameter3;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download