简体   繁体   中英

How can I add Nested Object List Properties to an existing Object

I'm trying to figure out how I can add an object list property to an existing object, which also has a list object property. I have 3 classes as FirstList, SecondList, and ThirdList with an Id and Text Property. ThirdList has a List Property of SecondList and SecondList has a List Property of FirstList. I've tried nesting.Add() but I can't get that to work.

//Classes

public class FirstList
{
    public int Id { get; set; }
    public string Text { get; set; }
}

public class SecondList
{
    public int Id { get; set; }
    public string Text { get; set; }
    public List<FirstList> Firsts { get; set; } = new List<FirstList>();
}

public class ThirdList
{
    public int Id { get; set; }
    public string Text { get; set; }
    public List<SecondList> Seconds { get; set; } = new List<SecondList>();

}

// program

ThirdList item = new ThirdList();

item.Id = 30;
item.Text = "Third Text";

item.Seconds.Add(new SecondList
{
    Id = 20,
    Text = "Second Text",
    Firsts.Add(new FirstList   //Trying to add a list object within the .Add method
    {
        Id = 10,
        Text = "First Text"
    })
});

// If I remove the 'Firsts' property from 'Seconds'.Add method and do the following below, I can  
//  add it afterwords. But, I was trying to see if it all could be added at once.

//  item.Seconds[0].Firsts.Add(new FirstList
// {
//     Id = 10,
//     Text = "First Text"
// });

List<T>.Add(T) method is used to add an object to the end of the List<T>. You have to instantiate the List<T> first before you use the.Add(T) method.

If I am not mistaken, what you are asking is how to initialize a list of objects. Take a look on below codes, notice the bracket { }.

        ThirdList item = new ThirdList()
        {
            Id = 30,
            Text = "Third Text",
            Seconds =
            {
                new SecondList
                {
                    Id = 20,
                    Text = "Second Text",
                    Firsts =
                    {
                        new FirstList
                        {
                            Id = 10,
                            Text = "First Text"
                        }
                    }
                }
            }
        };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM