0

With these classes. How would I add a new widget with a few components? The Component cannot be a List< Component> as the real world models are from a web service that has that structure. I've done this using a List but when I try and add the 'Widget' class to the models further up the chain it doesn't work as expected

public class Widget
{
  public int Id {get; set; }
  public string Name { get; set; }
  public Part[] parts { get; set; }
}

public class Part
{
  public int Id { get; set; }
  public string Name { get; set; }
}

Widget widget = new Widget {
  Id = 1,
  Name = TheWidget
};


foreach(var c in SomeArray)
{
  Part part = new Part()
  {
    component.Id = c.Id,
    component.Name = c.Name
  }
  // Add component to widget
  
}
NoIdea
  • 16
  • 3

1 Answers1

1

If you want to stick to existing Widget implementation, you can create a List<Part> and then convert it into the array:

using System.Linq;

...

List<Part> list = new List<Part>();

foreach(var c in SomeArray)
{
  Part part = new Part()
  {
    Id = c.Id,
    Name = c.Name
  }

  // Add component to a list, not widget (we can't easily add to array)
  list.Add(part);
}

// Having all parts collected we turn them into an array and assign to the widget
widget.parts = list.ToArray();

Linq will be a shorter:

widget.parts = SomeArray
  .Select(c => new Part() {
     Id = c.Id,
     Name = c.Name
   })
  .ToArray(); 

A better approach is to change Widget: let's collect parts into a list, not array

public class Widget
{
  public int Id {get; set; }
  public string Name { get; set; }
  public List<Part> Parts { get; } = new List<Part>();
}

then you can put

foreach(var c in SomeArray)
{
  Part part = new Part()
  {
    Id = c.Id,
    Name = c.Name
  }

  // Add component to widget
  widget.Parts.Add(part);
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215