【问题标题】:How to recursively check if the entity has a collection of children of that same entity?如何递归检查实体是否具有同一实体的子集?
【发布时间】:2021-09-30 04:10:50
【问题描述】:

所以我有一个节点,这意味着一行文本。代码如下:

public class Node : BaseEntity
{
    public string Name { get; set; }
    public int Position { get; set; }
    public Guid? ParentId { get; set; }
    public virtual Node Parent { get; set; }
    public virtual ICollection<Node> Children { get; set; }
}

这是应该的样子:

A. Blabla
   A.1 Meetings
       A.1.1 Standup
   A.2 Documents
       A.2.1 Wages
             A.2.1.1 Management
             A.2.1.1 Workers
B. Whatever
 ....

所以每个节点都会有它的名字,一个位置(A1,A2,等等...),如果它有一个它是父节点(除了最上面的节点,例如 A 和 B),如果它有子节点(对于示例 A 有孩子 A1、A2 等...)

如何递归检查节点是否有子节点,然后 foreach 那些子节点 => 如果这些子节点中的任何一个有子节点,等等...

例如,即使它有 7 层深......

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    据我所知,您基本上在那里有一个树结构。

    您已经拥有节点上的子节点信息,因此您可以查看this 帖子以了解如何遍历它们。

    您可以使用此代码从父级开始遍历您的树。

     public static void ProcessChildren(Node parent)
        {
            Console.WriteLine(parent.Position +" "+ parent.Name);
            foreach (Node node in parent.Children)
            {
                ProcessChildren(node);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-10
      • 2020-12-04
      • 1970-01-01
      • 2014-02-17
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多