这是我的模特
public class LinkModel
{
public string Name { get; set; }
public List<SubLinkModel> SubLinkName { get; set; }
}
public class SubLinkModel
{
public string Name { get; set; }
}
我正在编写以下代码以将数据分配给LinkModel
List<LinkModel> linkModel=new List<LinkModel> ();
linkModel.Add(new LinkModel { Name = "MainLink1", SubLinkName = new List<SubLinkModel> { } });
linkModel.Add(new LinkModel { Name = "MainLink2" });
我也希望将数据分配给SubLinkModel。
答案 0 :(得分:1)
您可以使用Collection Initializers完成此操作: -
List<LinkModel> linkModel = new List<LinkModel>
{
new LinkModel { Name = "MainLink1", SubLinkName = new List<SubLinkModel> { new SubLinkModel { Name = "foo" }, new SubLinkModel { Name = "bar" } } },
new LinkModel { Name = "MainLink2", ...
};
或者,如果您发现这个复杂的,那么您可以单独创建SubLink集合,然后添加它: -
List<SubLinkModel> SubLink1 = new List<SubLinkModel>
{
new SubLinkModel { Name = "foo1" },
new SubLinkModel { Name = "bar1" },
};
List<SubLinkModel> SubLink2 = new List<SubLinkModel>
{
new SubLinkModel { Name = "foo2" },
new SubLinkModel { Name = "bar2" },
};
..等等。
最后将其添加到主要集合中: -
List<LinkModel> linkModel = new List<LinkModel>
{
new LinkModel { Name = "MainLink1", SubLinkName = SubLink1 },
new LinkModel { Name = "MainLink2", SubLinkName = SubLink2 },
..and so on
};