0

this is my model

public class LinkModel
{
    public string Name { get; set; }
    public List<SubLinkModel> SubLinkName { get; set; }

}

public class SubLinkModel
{
    public string Name { get; set; }
}

I am writing the following code to assign data to LinkModel

List<LinkModel> linkModel=new List<LinkModel> ();
linkModel.Add(new LinkModel { Name = "MainLink1", SubLinkName = new List<SubLinkModel> { } });
linkModel.Add(new LinkModel { Name = "MainLink2" });

I want to assign data to SubLinkModel also.

1
  • Could you show an example what you mean? I'm not really sure what you want. You can assign values to SubLinkModel the same way you did with LinkModel. Commented Jan 6, 2016 at 7:23

1 Answer 1

1

You can simply do it with Collection Initializers like this:-

 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", ...
        };

Or if you find this complex then you can create the SubLink collection separately and then add it:-

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" },
                            };

..and so on.

Finally add it to the main collection:-

List<LinkModel> linkModel = new List<LinkModel>
            {
                new LinkModel { Name = "MainLink1", SubLinkName = SubLink1 },
                new LinkModel { Name = "MainLink2", SubLinkName = SubLink2 },
                ..and so on 
            };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.