c# - 从列表递归创建树

标签 c# generics recursion tree

我有一个基本上形成树的嵌套评论列表。

//Non-Relevant properties (Like Body, Creator etc) excluded
internal class Comment
{
    public int ID { get; set; }
    public int ItemID { get; set; }
    public int ParentItemID { get; set; }
    public List<Comment> ChildComments { get; set; }
}

首先,我从数据库中获取帖子列表,然后获取所有评论,其中ItemID == Posts[all].id

我想遍历一个平面列表并创建一个嵌套或树状列表。

它是这样的:

如果 ParentItemID == 0,那么我们有一个顶级评论。如果 ParentItemID > 0,我们需要将 ParentItemID 与评论 ID 匹配,并将子评论添加到父评论列表。

我卡住的地方是,我过去只使用递归来导航文件和文件夹。这不允许我实例化一个集合并通过后续递归保留它。

在递归之外实例化列表,然后每次我想添加一个项目时循环遍历所有项目,这似乎也很愚蠢。

我确信有一个很好的固定模式可以做到这一点,但我找不到它。

最佳答案

您可以循环遍历所有评论并获取每个评论的子评论:

foreach (Comment comment in comments) {
  comment.ChildComments =
    comments.Where(c => c.ParentItemID == comment.ItemID).ToList();
}

另一个性能更好的替代方案(如果需要的话)是将评论分组在 ParentItemID 上并创建一个 Dictionary<int, List<Comment>>从那里开始,然后像上面那样循环遍历评论并从字典中获取列表。

关于c# - 从列表递归创建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12168660/

相关文章:

c# - Web Api 返回扩展键值对象而不是原始 JSON 对象

匹配中的 Scala 尾递归优化

c# - ServiceStack Funq.Container 中相同接口(interface)的多个实现

Winforms DragDrop 的 C# DragEnter 事件

java - 使用 GSON 序列化 ArrayList(通用类型)

java - 具有可变参数类型的函数

ios - swift/iOS : Generics Error: protocol requires nested type 'V' ; do you want to add it?

python - 使用递归动态规划时如何填充背包表

C# 递归深度 - 你能走多深

c# - 使用 SendInput 模拟 XButton 输入