Initializing collections that contain nested colle

2020-05-02 16:41发布

How do I initialize a collection of 'Quote' objects based on the class shown below where 'Quote' would contain a collection of at least 5 'Rate' objects.

    List<Quote> quotes = new List<Quote> {new Quote { Id = 1, (need 5 Rate objects in here) } }

public class Quote
{
    public int Id { get; set; }
    public List<Rate> Rates { get; set; }
}

public class Rate
{
    public int Id { get; set; }
    public string AccommodationType { get; set; }
    public decimal Price { get; set; }
}

标签: c#
3条回答
狗以群分
2楼-- · 2020-05-02 17:23
List<Quote> quotes = new List<Quote> {
  new Quote { 
    Id = 1, 
    Rates = new List<Rate> {
      new Rate { Id = 1, ...},
      new Rate { Id = 2, ...},
      ...
    } 
  },
  ...
};
查看更多
干净又极端
3楼-- · 2020-05-02 17:28
List<Quote> quotes = new List<Quote> {
  new Quote { 
    Id = 1,
    Rates = new List<Rate> {
      new Rate {
        Id = 1,
        AccommodationType = "Whatever",
        Price = 0m
      },
      new Rate { ......
      }
    }
  }
};
查看更多
家丑人穷心不美
4楼-- · 2020-05-02 17:31

Use a factory method to create such object graphs for you.

查看更多
登录 后发表回答