Cast<> 用于分层数据结构



下面是一个例子

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
}

我最初的问题是模型中的分层数据A,必须在视图中显示,因此我必须在ViewModel中使用INotifyPropertyChanged等创建B类型。对于分层数据,从AB的转换似乎比简单的linq Cast<>更复杂。

如果有人想要编码,那么这里有一个很漂亮的函数,可以这样使用:

foreach (var item in b.Flatten(o => o.Children).OrderBy(o => o.Text))
    Console.WriteLine(item.Text);

使用递归函数将A转换为B

B BFromA(A a) {
    return new B { Text = a.Text, Children = a.Children.Select(BFromA).ToList() };
}

用法:

B[] b = a.Select(BFromA).ToArray();  // convert a to b type

最新更新