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
  
}
1
  • "complains about"? Error details are usually very helpful to diagnose a problem. Commented May 20, 2022 at 11:41

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.