如题所示,比如有一个树形结构的数据,节点为 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; }
}
}
对代码感兴趣的的欢迎关注微信公众号爱游戏爱编程,一起进步呀。