我有一个类似的课程:
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
答案 0 :(得分:2)
我只是递归地将树转换为新类型:
miniChannel Convert(Channel ch)
{
return new miniChannel
{
title = ch.Title,
key = ch.Guid.ToString(),
children = ch.Children.Select(Convert).ToList()
};
}