Si8 Si8 - 2 years ago 71
C# Question

How to populate a List which has a class within a class

JSON:

{
"Col1": "John",
"Col2": "Doe",
"Col3Combined": [
{
"Col3": "12",
"Col4Combined": [
{
"Col4": "156-345"
}
],
"Col5Combined": [
{
"Col5": "792-098"
}
]
}
]
},
{
"Col1": "Mike",
"Col2": "Keller",
"Col3Combined": [
{
"Col3": "12",
"Col4Combined": [
{
"Col4": "145-394"
}
],
"Col5Combined": [
{
"Col5": "156-323"
}
]
},
{
"Col3": "15",
"Col4Combined": [
{
"Col4": "909-203"
}
],
"Col5Combined": [
{
"Col5": "121-444",
"Col5": "134-232"
}
]
}
]
}


C# classes:

public class Col4Combined
{
public string Col4 { get; set; }
}

public class Col5Combined
{
public string Col5 { get; set; }
}

public class Col3Combined
{
public string Col3 { get; set; }
public List<Col4Combined> Col4Combined { get; set; }
public List<Col5Combined> Col5Combined { get; set; }
}

public class RootObject
{
public string Col1 { get; set; }
public string Col2 { get; set; }
public List<Col3Combined> Col3Combined { get; set; }
}


I am doing the following:

List<RootObject> lr = new List<RootObject>();
lr.Add(new RootObject
{
Col1 = "test",
Col2 = "test2",
Col3Combined = new List<Col3Combined>(); //but then how do I populate it?
}
);


How can I populate
Col3Combined
in the list above.

Answer Source

You can use the collection initializer for that:

lr.Add(new RootObject
{
    Col1 = "test",
    Col2 = "test2",
    Col3Combined = new List<Col3Combined>
    {
        new Col3Combined(),
        // And others
    }
});

Basically you can do it all the way:

var lr = new List<RootObject>
{
    new RootObject
    {
        Col3Combined = new List<Col3Combined>
        {
            new Col3Combined
            {
                Col4Combined = new List<Col4Combined>
                {
                    new Col4Combined { Col4 = "some string" }
                },
                Col5Combined = new List<Col5Combined>
                {
                    new Col5Combined { Col5 = "some other string" }
                }
            }
            // And others
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download