locked
List of different types: How to do it. RRS feed

  • Question

  • User-751688132 posted

    Hi!

    I have in my project two classes: User and Entity. I want to create a List of List of these classes. Bellow what i tried.

    I

    List<User> lu = new List<User>();
    List<Entity> le = new List<Entity>();
    
    User a = new User();
    User b = new User();
    User c = new User();
    User d = new User();
    
    Entity w = new Entity();
    Entity x = new Entity();
    Entity y = new Entity();
    Entity z = new Entity();
    
    lu.Add(a);
    lu.Add(b);
    lu.Add(c);
    lu.Add(d);
    
    le.Add(w);
    le.Add(x);
    le.Add(y);
    le.Add(z);
    
    //This part dont work!
    List<List<dynamic>> l = new List<List<dynamic>>();
    l.Add(lu);
    l.Add(le);

    To see the list i do:

    foreach (var p in ViewBag.usrs)
    {
        <tr>
            <td>@p.Name</td>
            <td>@p.LasName</td>
        </tr>
    }
    How can i do that with two type of objects?

    How do i do that?

    Sunday, October 15, 2017 1:14 AM

All replies

  • User-335504541 posted

    Hi claudiogc,

    What the ViewBag.usrs? Dose it the List<List<dynamic>> l?

    Do you want to let ViewBag.usrs contains both User list and Entity list?

    You could try to declare a new interface and have both types implement it.

    For example:

        public interface UserEntity
        {
             string Name { get; set; }
             string LastName { get; set; }
        }
    
        class User : UserEntity
        {
            public string Name { get; set; }
            public string LastName { get; set; }
        }
    
    
        class Entity : UserEntity
        {
            public string Name { get; set; }
            public string LastName { get; set; }
        }
    
    
                List<UserEntity> UserEntity = new List<UserEntity>();
                User u = new User();
                u.Name = "UName";
                u.LastName = "ULastName";
                Entity e = new Entity();
                e.Name = "EName";
                e.LastName = "ELastName";
                UserEntity.Add(u);
                UserEntity.Add(e);
                ViewBag.usrs = UserEntity;
    

    In the view:

    @{
        List<UserEntity> usrs =(List<UserEntity>)ViewBag.usrs;
    }
    
    
    <table>
    @foreach (var a in usrs)
    {
        <tr>
            <td>@a.Name</td>
            <td>@a.LastName</td>
        </tr>
    
    }</table>

    Best Regards,

    Billy

    Monday, October 16, 2017 8:25 AM