0

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"
// });
1
  • Use a variable for the SecondList instance and call Firsts.Add from that variable instead (same as your ThirdList instance). Commented Jan 17, 2023 at 23:57

1 Answer 1

2

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