Search code examples
c#classtraversal

Traverse class Tree and convert to the needed type


i have a class similar to this:

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

i need to convert this class tree to a the same tree structure, but with less properties (and different names for the properties) i.e:

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
}

i was thinking it would be easy traversing the tree with the following function:

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;
        }
    }
}

how should i change the function so i could return a IEnumerable<miniChannel> or, alternatively, is there some other way to do it? Please notice that i cannot change the source class Channel


Solution

  • I'd just recursively convert the tree to the new type:

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