Here is an example
class A
{
public string Text = "";
public IEnumerable<A> Children = new List<A>();
}
class B
{
public string Text;
public IEnumerable<B> Children = new List<B>();
}
static void Main(string[] args)
{
// test
var a = new A[]
{
new A() { Text = "1", Children = new A[]
{
new A() { Text = "11"},
new A() {Text = "12"},
}},
new A() { Text = "2", Children = new A[]
{
new A() {Text = "21", Children = new A[]
{
new A() {Text = "211"},
new A() {Text = "212"},
}},
new A() {Text = "22"},
}},
};
B[] b = a ...; // convert a to b type
}
My original problem is hierarchical data A
in Model, which has to be displayed in the View, thus I have to create B
type in ViewModel with INotifyPropertyChanged
, etc. Converting from A
to B
for hierarchical data seems more complicated than a simple linq Cast<>
.
If somebody is going to try to code, then here is the nice flattering function, can be used like this:
foreach (var item in b.Flatten(o => o.Children).OrderBy(o => o.Text))
Console.WriteLine(item.Text);