C# 通过某一个节点ID获取所有的当前分支的所有节点

如题所示,比如有一个树形结构的数据,节点为 1、1_1、1_2、1_1_1、1_1_2,如果只通过其中一个节点,获取所有的家族成员呢?

思路:首先通过递归获取该节点了一级节点,然后在通过递归找该节点下的所有节点即可。
首先我们定义一个类,包含三个属性。

class Node
    {
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Name { get; set; }
    }

然后是获取一级节点ID的方法。

  public static int getTopId(int id, List<Node> nodeList)
        {
            var node = nodeList.FirstOrDefault(c => c.Id == id);
            if (node.ParentId == 0) //判断是不是一级节点。
            {
                return node.Id;
            }
            else
            {
                return getTopId(node.ParentId, nodeList);
            }
        }

接着就是递归,取所有的节点。

  public static List<Node> GetSonNode(int id,List<Node> nodeList)
        {
            var query = nodeList.Where(c => c.ParentId == id);

            return query.ToList().Concat(query.ToList().SelectMany(t => GetSonNode(t.Id, nodeList))).ToList();
        }

好了,完整代码如下。

using System;
using System.Collections.Generic;
using System.Linq;

namespace GetAllNodeById
{
    class Program
    {
        static void Main(string[] args)
        {
            var nodeList = new List<Node>() { 
                new Node{ Id=1,ParentId=0,Name="1"},
                new Node{ Id=2,ParentId=0,Name="2"},
                new Node{ Id=3,ParentId=1,Name="1_1"},
                new Node{ Id=4,ParentId=1,Name="1_2"},
                new Node{ Id=5,ParentId=3,Name="1_1_1"},
                new Node{ Id=6,ParentId=5,Name="1_1_1_1"},
            };
            int id = 6;
            var topId = getTopId(id, nodeList);
            var list = GetSonNode(topId, nodeList);

            foreach (var item in list)
            {
                Console.WriteLine(item.Name);
            }
            Console.ReadKey();
        }
        public static int getTopId(int id, List<Node> nodeList)
        {
            var node = nodeList.FirstOrDefault(c => c.Id == id);
            if (node.ParentId == 0)
            {
                return node.Id;
            }
            else
            {
                return getTopId(node.ParentId, nodeList);
            }
        }
        public static List<Node> GetSonNode(int id,List<Node> nodeList)
        {
            var query = nodeList.Where(c => c.ParentId == id);

            return query.ToList().Concat(query.ToList().SelectMany(t => GetSonNode(t.Id, nodeList))).ToList();
        }
    }
    class Node
    {
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Name { get; set; }
    }
}

对代码感兴趣的的欢迎关注微信公众号爱游戏爱编程,一起进步呀。

6375263-6433dbc4df85104a.jpg
爱游戏爱编程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李公子lm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值