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.
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
}
}
.SortByto sort the elements bySpeedproperty. - Afzaal Ahmad ZeeshanNameproperty. You may move these properties to an abstract base class and inherit from this one. - mm8Machineand then have classTram : Machineand so on - JohnPete22