这是在重构园子博客后台多级分类的实现代码时遇到的一个问题,从数据库中获取一个博客的所有博文分类列表保存在 List<Category>
,其中既有 internal node,也有 leaf node
internal node 的特点是存在某个 category 的 ParentId 等于 internal node 的 CategoryId
leaf node 的特点是没有任何 category 的 ParentId 等于 leaf node 的 CategoryId
请问如何在 C# List 中快速简单找出所有 leaf node?
我理解是一个list中通过CategoryId <- ParentId 构建的一个树结构 现在寻找所有叶子节点
下面这是AI输出的
// 假设 Category 类定义如下:
public class Category
{
public int CategoryId { get; set; }
public int? ParentId { get; set; }
// 其他属性...
}
// 获取所有分类列表
List<Category> allCategories = GetCategoriesFromDatabase();
// 找出所有作为父节点的 CategoryId
HashSet<int> parentIds = new HashSet<int>(
allCategories
.Where(c => c.ParentId.HasValue)
.Select(c => c.ParentId.Value)
);
// 找出所有叶子节点(没有任何节点以它们为父节点)
List<Category> leafNodes = allCategories
.Where(c => !parentIds.Contains(c.CategoryId))
.ToList();
不需要用 HashSet ,Select 之后 Distinct 就可以了
采用这个方法,用下面的代码解决了
var allCategories = await Get(blogId, type)
.ProjectToType<T>()
.ToListAsync();
var parentIds = allCategories
.Where(c => c.ParentId != null)
.Select(c => c.ParentId)
.Distinct();
var leafCategories = allCategories
.Where(c => !parentIds.Contains(c.CategoryId))
.ToList();
初始化一个 Dictionary<Id, Node>
循环两次
第一次
从dict 获取自己,不存在把自己加到 dict 里面,存在更新自己除了children 外的其他参数
从Dict获取 parentId 不存在就初始化一个,children 加自己
第二次 遍历 Dict 的 values 按 children 是否为空找