gpt4 book ai didi

c# - 递归 LINQ 查询 : select item and all children with subchildren

转载 作者:可可西里 更新时间:2023-11-01 08:16:11 26 4
gpt4 key购买 nike

有没有什么方法可以编写一个 LINQ(或过程式)查询,它可以通过一个查询选择一个项目和所有子项?我有实体:

public class Comment
{
public int Id {get;set;}
public int ParentId {get;set;}
public int Text {get;set;}
}

我有一个 ID,所以我想选择带有 ID 的 Comment 及其所有子项和子项。示例:

1
-2
--3
-4
-5
--6
2
3

如果 ID == 1 那么我想要 1,2,3,4,5,6 的列表。

最佳答案

   public class Comment
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Text { get; set; }
public List<Comment> Children { get; set; }
}

class Program
{
static void Main()
{
List<Comment> categories = new List<Comment>()
{
new Comment () { Id = 1, Text = "Item 1", ParentId = 0},
new Comment() { Id = 2, Text = "Item 2", ParentId = 0 },
new Comment() { Id = 3, Text = "Item 3", ParentId = 0 },
new Comment() { Id = 4, Text = "Item 1.1", ParentId = 1 },
new Comment() { Id = 5, Text = "Item 3.1", ParentId = 3 },
new Comment() { Id = 6, Text = "Item 1.1.1", ParentId = 4 },
new Comment() { Id = 7, Text = "Item 2.1", ParentId = 2 }
};

List<Comment> hierarchy = new List<Comment>();
hierarchy = categories
.Where(c => c.ParentId == 0)
.Select(c => new Comment() {
Id = c.Id,
Text = c.Text,
ParentId = c.ParentId,
Children = GetChildren(categories, c.Id) })
.ToList();

HieararchyWalk(hierarchy);

Console.ReadLine();
}

public static List<Comment> GetChildren(List<Comment> comments, int parentId)
{
return comments
.Where(c => c.ParentId == parentId)
.Select(c => new Comment {
Id = c.Id,
Text = c.Text,
ParentId = c.ParentId,
Children = GetChildren(comments, c.Id) })
.ToList();
}

public static void HieararchyWalk(List<Comment> hierarchy)
{
if (hierarchy != null)
{
foreach (var item in hierarchy)
{
Console.WriteLine(string.Format("{0} {1}", item.Id, item.Text));
HieararchyWalk(item.Children);
}
}
}

关于c# - 递归 LINQ 查询 : select item and all children with subchildren,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21262391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com