interface IWidget
{
string Name { get; set; }
int Weight { get; }
}
class Screw : IWidget
{
public string Name { get; set; }
public int Weight {
get; } = 250;
public Screw(string name)
=> Name = name;
}
class Bolt :
IWidget
{
public string Name { get; set; }
public int Weight {
get; } = 100;
public Bolt(string name)
=> Name = name;
}
class Dunnage : IWidget
{
public IEnumerable<IWidget> Widgets { get; set; }
public string Name { get; set; }
public int Weight
{
get
{
int total = 0;
foreach (var w in Widgets)
total += w.Weight;
return total;
}
}
}
now in our main we can lump our individual widgets in with the Dunnage in one shipment collection.
class Program
{
static void Main(string[] args)
{
IWidget widget0 = new Screw("foo");
IWidget widget1 = new Bolt("bar");
IWidget dunnage1 = new Dunnage {
Name = "Bin A",
Widgets = new IWidget[] { new Screw("bill"), new Screw("foo"), new Bolt("bar")}};
var shipment = new
List<IWidget>(new
IWidget[] { widget0, widget1, dunnage1 });
var totalWeight = shipment.Select(w=> w.Weight).Aggregate((x, y)
=> x += y);
Console.WriteLine(totalWeight);
}
}