1、前言
最近在项目中遇到一个问题:根据某单位的Id
查询该单位及其下属的所有子孙单位。这是一个典型的根据Id
和ParentId
进行递归查询的场景,下面就来说一说如何在Linq
中实现它。
2、递归查询
新建一个Entity
类,代码如下:
using System.Collections.Generic;
namespace App
{
public class Entity
{
/// <summary>
/// 单位Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// 父单位Id
/// </summary>
public int ParentId { get; set; }
/// <summary>
/// 单位名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 子节点
/// </summary>
public List<Entity> Entities { get; set; }
}
}
递归查询代码如下:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace App
{
class Program
{
static void Main(string[] args)
{
List<Entity> list = new List<Entity>();
list.Add(new Entity { Id = 1, ParentId = 0, Name = "总公司" });
list.Add(new Entity { Id = 2, ParentId = 1, Name = "子公司A" });
list.Add(new Entity { Id = 3, ParentId = 1, Name = "子公司B" });
list.Add(new Entity { Id = 4, ParentId = 2, Name = "部门A1" });
list.Add(new Entity { Id = 5, ParentId = 2, Name = "部门A2" });
list.Add(new Entity { Id = 6, ParentId = 3, Name = "部门B1" });
list.Add(new Entity { Id = 7, ParentId = 3, Name = "部门B2" });
// 查询
int id = 1;
Entity entity = GenerateEntityNode(list, id);
// 打印
string json = JsonConvert.SerializeObject(entity, Formatting.Indented);
Console.WriteLine(json);
Console.ReadKey();
}
// 递归查询
static Entity GenerateEntityNode(List<Entity> list, int id)
{
// 查询本单位
Entity entity = list.Where(p => p.Id == id).FirstOrDefault();
if (entity == null)
{
return entity;
}
// 查询子单位
entity.Entities = list.Where(p => p.ParentId == id).ToList();
// 对子单位进行递归
foreach (var item in entity.Entities)
{
GenerateEntityNode(list, item.Id);
}
return entity;
}
}
}
运行结果如下所示:
{
"Id": 1,
"ParentId": 0,
"Name": "总公司",
"Entities": [
{
"Id": 2,
"ParentId": 1,
"Name": "子公司A",
"Entities": [
{
"Id": 4,
"ParentId": 2,
"Name": "部门A1",
"Entities": []
},
{
"Id": 5,
"ParentId": 2,
"Name": "部门A2",
"Entities": []
}
]
},
{
"Id": 3,
"ParentId": 1,
"Name": "子公司B",
"Entities": [
{
"Id": 6,
"ParentId": 3,
"Name": "部门B1",
"Entities": []
},
{
"Id": 7,
"ParentId": 3,
"Name": "部门B2",
"Entities": []
}
]
}
]
}
如果设置int id = 2
,则运行结果如下所示:
{
"Id": 2,
"ParentId": 1,
"Name": "子公司A",
"Entities": [
{
"Id": 4,
"ParentId": 2,
"Name": "部门A1",
"Entities": []
},
{
"Id": 5,
"ParentId": 2,
"Name": "部门A2",
"Entities": []
}
]
}