How can I add DTO to List Object using c#

I have to add the Value object to List how can I do that.This is my DTO

public class Root    {
    public List<Value> Value { get; set; } 
    public Count Count { get; set; } 
}
public class Value    {
    public string Value1 { get; set; } 
    public string Value2 { get; set; } 
}

public class Count    {
    public int Total { get; set; } 
}

1 answer

  • answered 2021-02-20 06:22 Athanasios Kataras

    By following these simple steps:

    // Create a Root object
    var root = new Root {
        // Initialize the empty list
        Value = new List<Value>()
    };
    // Create a new Value object
    var value = new Value {
        Value1 = "",
        Value2 = ""
    };
    // Add the value to the list
    root.Value.Add(value);
    

    Just a suggestion, when you have lists of something consider using plural (Values instead of Value)

    public List<Value> Values { get; set; } 
    

    Edit based on comment

    var valueList = new Root(); 
    
    // Add this row
    valueList.Value = new List<Value>();
    valueList.Value.Add(new Value() { Value1 = "One", Value2 = "Two" });
    valueList.Value.Add(new Value() { Value1 = "Three", Value2 = "Four" });