在.NET 9中,Linq增加了一些新的功能和优化,支持更灵活和高效的递归查询。以下是一个递归查询的高级用法示例,假设我们有一个表示公司组织结构的树形数据结构。我们可以使用Linq递归来查找所有子节点或计算从根节点到特定节点的路径。
示例代码
using System;
using System.Collections.Generic;
using System.Linq;
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int? ManagerId { get; set; } // 如果为 null,表示该员工为顶级领导
}
public class Program
{
// 模拟数据库或数据源
private static List<Employee> employees = new List<Employee>
{
new Employee { Id = 1, Name = "CEO", ManagerId = null },
new Employee { Id = 2, Name = "VP of Sales", ManagerId = 1 },
new Employee { Id = 3, Name = "VP of Marketing", ManagerId = 1 },
new Employee { Id = 4, Name = "Sales Manager", ManagerId = 2 },
new Employee { Id = 5, Name = "Sales Rep", ManagerId = 4 },
new Employee { Id = 6, Name = "Marketing Manager", ManagerId = 3 }
};
public static void Main()
{
// 示例1: 查找所有子节点
int managerId = 1; // 从CEO开始查找
var allSubordinates = GetAllSubordinates(managerId);
Console.WriteLine("All subordinates:");
foreach (var emp in allSubordinates)
{
Console.WriteLine($"- {emp.Name}");
}
// 示例2: 获取从CEO到特定员工的路径
int employeeId = 5; // 查找“Sales Rep”的路径
var pathToEmployee = GetPathToEmployee(employeeId);
Console.WriteLine("\nPath to employee:");
foreach (var emp in pathToEmployee)
{
Console.WriteLine($"- {emp.Name}");
}
}
// 使用递归的Linq查找所有子节点
private static IEnumerable<Employee> GetAllSubordinates(int managerId)
{
return employees
.Where(e => e.ManagerId == managerId)
.SelectMany(e => new[] { e }.Concat(GetAllSubordinates(e.Id))); // 递归获取子节点
}
// 使用递归的Linq获取从根节点到特定节点的路径
private static IEnumerable<Employee> GetPathToEmployee(int employeeId)
{
var employee = employees.FirstOrDefault(e => e.Id == employeeId);
if (employee == null) yield break;
foreach (var manager in GetPathToEmployee(employee.ManagerId ?? 0))
yield return manager;
yield return employee;
}
}
代码解释
- GetAllSubordinates 方法递归查找所有子节点,通过
SelectMany拼接结果列表。 - GetPathToEmployee 方法递归查找路径,通过
yield return构建从根节点到指定节点的路径。
输出结果
运行上面的代码,将会输出类似以下内容:
All subordinates:
- VP of Sales
- Sales Manager
- Sales Rep
- VP of Marketing
- Marketing Manager
Path to employee:
- CEO
- VP of Sales
- Sales Manager
- Sales Rep
这样,通过Linq递归,可以轻松构建复杂的组织结构查询逻辑。
1899

被折叠的 条评论
为什么被折叠?



