简体   繁体   English

如何将嵌套的 Object 列表属性添加到现有的 Object

[英]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.我想弄清楚如何将 object 列表属性添加到现有的 object,它也有一个列表 object 属性。 I have 3 classes as FirstList, SecondList, and ThirdList with an Id and Text Property.我有 3 个类,分别是 FirstList、SecondList 和 ThirdList,它们具有 Id 和 Text 属性。 ThirdList has a List Property of SecondList and SecondList has a List Property of FirstList. ThirdList 具有 SecondList 的列表属性,SecondList 具有 FirstList 的列表属性。 I've tried nesting.Add() but I can't get that to work.我试过 nesting.Add() 但我无法让它工作。

//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>. List<T>.Add(T) 方法用于将 object 添加到 List<T> 的末尾。 You have to instantiate the List<T> first before you use the.Add(T) method.在使用 .Add(T) 方法之前,您必须先实例化 List<T>。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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