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

4

1 回答 1

2

我只是递归地将树转换为新类型:

miniChannel Convert(Channel ch)
{
    return new miniChannel
    {
        title = ch.Title,
        key = ch.Guid.ToString(),
        children = ch.Children.Select(Convert).ToList()
    };
}
于 2012-11-14T13:00:49.573 回答