将项添加到嵌套列表

时间:2016-11-02 09:38:04

标签: c#

我有以下课程:

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Parent> Children { get; set; }
}

从父母那里我可以有多个孩子,每个孩子都可以有更多的孩子等等。

现在我的目标是以分层形式填充此对象/列表。我从顶部开始并慢慢添加到它上面以便分支出来,但是我有一个问题。如何找到并向特定孩子添加项目?

编辑: 已经提供了几种方法来查找该节点并添加到该节点。但问题仍然存在:

考虑一下:我有一个已经有几个孩子的父母。我将使用Find方法查找其中一个子项,并使用返回Child的方法。现在我需要在父母身上为孩子添加一个新孩子。当我使用你的代码时,它将Child添加到Child中,方法Find返回,但它不会影响我原来的Parent。当我想要让我新添加的孩子时,该父母的孩子名单仍为0。

抽出示例:这是我已经拥有的列表

- Mary    
    - Peter
        - Jake
    - Luke

在这个例子中,玛丽有两个孩子,彼得和卢克。彼得有个孩子,杰克。我的目标是找到杰克,并为杰克增添一个孩子。我可以通过使用递归搜索来完成此操作,这将成功返回Jake。我可以给杰克添加一个孩子(约翰),这将留给我这个:

- Jake
    - John

但是我需要修改原始父母,以便我有:

- Mary
    - Peter
       - Jake
           - John
  - Luke

3 个答案:

答案 0 :(得分:1)

您需要在树中递归搜索您的节点:

[{"id":"aaa","map1count":"1","map2count":"2","map3count":"0"},
 {"id":"bbb","map1count":"1","map2count":"0","map3count":"0"},
 {"id":"ccc","map1count":"1","map2count":"0","map3count":"6"},
 {"id":"ddd","map1count":"0","map2count":"0","map3count":"6"}]

用法示例(public static Parent FindNode(int id, Parent current) { if (current.Id == id) { return current; } foreach (var child in current.Children) { var ret = FindNode(id, child); if (ret != null) { return ret; } } return null; } 表示树的根节点):

root

答案 1 :(得分:0)

你必须编写一个递归函数来完成它。您将首先获得最顶级Parent的子项,然后将子项作为参数传递给下面的函数&#34; GetParendetails&#34;

   public Parent GetDetails()
   {
       //the following code should be replaced by the code to get Top parent details from your db or whatever. pass the children of this class to the below function
      Parent P=new Parent();
      P.Id=1;
      p.Name="Top";
      P.Children=new List<Parent>();
      P.Children.Add(new Parent(2,"test1"));
      P.Children.Add(new Parent(2,"test2"));
      P.Children.Add(new Parent(2,"test3"));
      P.Children=GetParendetails(P.Children);

   }


   public List<Parent> GetParendetails(List<Parent> PL)
   {
      if(PL!=null)
      {
          foreach(Parent P in PL)
          {
             List<Parent> childlist=new List<Parent>();
              //logic to get children of P and adding them to childlist
               P.Children=GetParendetails(childlist);
          }
      }
      return PL;
   }

答案 2 :(得分:0)

您的项目应包含ParentId属性,然后您可以使用LINQ构建树

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
    public List<Parent> Children { get; set; }
}

要构建树,只需使用LINQ

public IEnumerable<Item> BuildTree( IEnumerable<Item> source )
{
    // build the children list for each item
    foreach ( var item in source )
    {
        item.Children = source.Where( i => i.ParentId == i.Id ).Tolist();
    }
    // return only the root parents
    return source.Where( i => i.ParentId == 0 ).ToList();
}
相关问题