2012-11-14 26 views
0

我有一個類似的類:遍歷類樹和轉換爲所需要的類型

public class Channel 
{ 
    public string Title {get;set;} 
    public Guid Guid {get;set;} 
    public List<Channel> Children {get;set;} 
    // a lot more properties here 
} 

我需要這個分類轉換爲相同的樹狀結構, 但較少的屬性(和不同的名字對於屬性) 即:

public class miniChannel 
{ 
    public string title {get;set;} 
    public string key {get;set;} 
    public List<miniChannel> children {get;set;} 
    // ALL THE OTHER PROPERTIES ARE NOT NEEDED 
} 

我想它會很容易穿越用下面的函數樹:

public IEnumerable<MyCms.Content.Channels.Channel> Traverse(MyCms.Content.Channels.Channel channel) 
{ 
    yield return channel; 
    foreach (MyCms.Content.Channels.Channel aLocalRoot in channel.Children) 
    { 
     foreach (MyCms.Content.Channels.Channel aNode in Traverse(aLocalRoot)) 
     { 
      yield return aNode; 
     } 
    } 
} 

我應該如何更改功能,以便我可以返回IEnumerable<miniChannel> 或者,還有其他方法可以做到嗎? 請注意,我不能改變源類Channel

回答

2

我只是樹遞歸地轉換爲新類型:

miniChannel Convert(Channel ch) 
{ 
    return new miniChannel 
    { 
     title = ch.Title, 
     key = ch.Guid.ToString(), 
     children = ch.Children.Select(Convert).ToList() 
    }; 
} 
+0

OMG,這就是這麼簡單,我覺得這麼愚蠢。 – Dementic

相關問題