share
Stack OverflowIterate over classes with different structure
[0] [1] justme
[2019-08-20 14:08:17]
[ c# ]
[ https://stackoverflow.com/questions/57575536/iterate-over-classes-with-different-structure ]

I need to show instances of above classes in HTML table. All objects should be ordered by speed property.

public class Bus { public float Speed {get; set;} public string Name {get; set;}}
public class Tram { public float Speed {get; set;} public string Name {get; set;}}
public class Car { public float Speed {get; set;} public string Name {get; set;}}
public class Bike 
{ 
    public float Speed {get; set;}
    public string Name {get; set;}
    public double Height {get; set;}
    public double Width {get; set;}
}

Table looks like:

  Name | Speed | Height | Width

Bus    |   180   |            |
Bus    |   179   |            |
Bike   |   30    |    23      |  32
Tram   |   23    |            |

How I could iterate over this objects and then display them? Should I implement some interface? It would be extremly easy if all classes has the same fields but in this case, Bike class has four properties.

You need to use reflection - Renat
(1) Can you introduce a parent class here? That will help you utilize LINQ and do something like, .SortBy to sort the elements by Speed property. - Afzaal Ahmad Zeeshan
(1) @mjwills: And a Name property. You may move these properties to an abstract base class and inherit from this one. - mm8
(2) Create a base class the have properties Name, Speed, Height, Width which will make it easy to iterate. - jdweng
(1) Base class Machine and then have class Tram : Machine and so on - JohnPete22
[+2] [2019-08-20 14:25:08] kaffekopp

Start by identifying common properties of your concepts when creating your model. You can create an abstract base class (in my example named "Vehicle") with the common properties, and then inherit in in the sub classes:

public abstract class Vehicle
{
    public string Name { get; set; }
    public float Speed { get; set; }
}

public class Bus : Vehicle { }
public class Tram : Vehicle { }
public class Car : Vehicle { }
public class Bike : Vehicle
{
    public double Width { get; set; }
    public double Height { get; set; }
}

You can then iterate a collection of the base class type and type check every instance before handling it:

var vehicles = new List<Vehicle>
{
    new Bus { Name = "Bus", Speed = 180 },
    new Bus { Name = "Bus", Speed = 179 },
    new Bike { Name = "Bus", Speed = 180, Height = 23, Width = 32 },
    new Tram { Name = "Bus", Speed = 23 }
};

foreach (var vehicle in vehicles)
{
    // ..Output vehicle.Name & vehicle.Speed
    if (vehicle is Bike bike)
    {
        // Output bike.Height & bike.Width
    }
}

1