C# multi level object and list access
c#, oop
Solution
var msg = new Message {
Pages = new List<Page> {
new Page {
Lines = new List<Line> { new Line { Text = "Test" } }
}
}
};
Note: if the lists are initialized in their respective constructors, you can remove the `new List<>` bits:
var msg = new Message {
Pages = {
new Page {
Lines = { new Line { Text = "Test" } }
}
}
};
You could also add an implicit conversion operator from `string` to `Line`, in which case:
var msg = new Message {
Pages = {
new Page {
Lines = { "Test" }
}
}
};
Edit: fully working example, including operator and ctor initialization, and multiple pages (see comments):
using System.Collections.Generic;
public class Message {
public List<Page> Pages { get; private set; }
public Message() { Pages = new List<Page>(); }
}
public class Page {
public List<Line> Lines { get; private set; }
public Page() { Lines = new List<Line>(); }
}
public class Line {
public string Text { get; private set; }
public static implicit operator Line(string value) {
return new Line { Text = value };
}
}
static class Program {
static void Main() {
var msg = new Message {
Pages = {
new Page {
Lines = { "Test" }
},
new Page {
Lines = {
"On another page",
"With two lines"
},
}
}
};
}
}
Problem
I have no idea what should this question be titled nor keyword to search. Scenario: I have a model as below ``` public class Message { public List<Page> Pages { get; set; } public class Page { public List<Line> Lines { get; set; } public class Line { public string Text {get; set; } ``` When I wanted to insert a `Line` with `Text = "Test"` at `Page` 1, I would need to do the following. ``` var Message = new Message(); var line = new Line { Text = "Test" }; var page = new Page(); page.Lines.Add(line); Message.Pages.Add(page); ``` Question: are there any easier way to achieve this? Eg. ``` Message.Pages[0].Lines[0].Text = "Test"; ``` Thanks. Edit: Assumed all properties are properly instantiated in constructors.