如何在C#中转换以下内容?

时间:2014-03-06 01:52:06

标签: c# .net

我有以下型号

public class Node
    {
        public int AutoIncrementId { get; set; }


        public string Text { get; set; }


        public List<Node> Nodes { get; set; }

          ...//other propeties

     }

我想将数据转换为以下模型,

public class TreeView
{    
 public int Id {get; set;}
 public string Text {get; set;}
 public List<TreeView> Items {get; set;}    
}

我从以下开始,但后来意识到我怎么知道何时停止?

变量test保存节点数据

var items = test.Data.Select(x => new TreeViewItemModel
   {
     Id = x.AutoIncrementId.ToString(),
     Text = x.Text,
     Items =   x.Nodes.Select(y=> new TreeViewItemModel(
     {

       Id =  y.AutoIncrementId.ToString(),
       Text =  y.Text,
       Items = //do I keep going? 

     }));    
  }    
);

3 个答案:

答案 0 :(得分:2)

您可以使用递归来执行此操作:

public TreeView ConvertToTreeView(Node node)
{
    TreeView tv = new TreeView();

    tv.Id = node.AutoIncrementId;
    tv.Text = node.Text;
    if (node.Nodes != null && node.Nodes.Count > 0)
    {
        tv.Items = new List<TreeView>();
        node.Nodes.ForEach(x => tv.Items.Add(ConvertToTreeView(x)));
    }

    return tv;
}

答案 1 :(得分:0)

我更喜欢这种形式。

public TreeView ConvertToTreeView(Node node)
{
    return new TreeView
            {

                Id = node.AutoIncrementId;
                Text = node.Text;
                Items = node.Nodes.Select(ConvertToTreeView).ToList()
            };
}

编辑:是Baldrick,我做了:P和

public TreeView ConvertToTreeView(Node node)
{
    return new TreeView
            {

                Id = node.AutoIncrementId;
                Text = node.Text;
                Items = node.Nodes != null
                           ? node.Nodes.Select(ConvertToTreeView).ToList()
                           : new List<TreeView>()
            };
}

看起来不太好。

答案 2 :(得分:0)

为了清晰和简洁,这很好用:

public TreeView ConvertNode(Node rootNode)
{
    var tree = new TreeView
    {
        Id = rootNode.AutoIncrementId,
        Text = rootNode.Text,
        Items = new List<TreeView>()
    };

    if (rootNode.Nodes != null)
    {
        foreach (var node in rootNode.Nodes)
        {
            tree.Items.Add(ConvertNode(node));
        }
    }

    return tree;
}