簡體   English   中英

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 ,該數據必須在視圖中顯示,因此我必須在IModel中使用INotifyPropertyChanged等創建B類型。對於層次結構數據,從A轉換為B似乎比簡單的linq Cast<>要復雜。 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM