Cast<> 用于分层数据结构

Cast<> for hierarchical data structure

这是一个例子

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 中创建 B 类型 INotifyPropertyChanged,等等。将分层数据从 A 转换为 B 似乎比简单的 linq Cast<>.

更复杂

如果有人要尝试编码,那么here是一个很好的讨人喜欢的功能,可以这样使用:

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