获取 LINQ 列表中的所有子项

And*_*ici 2 c# linq

我有一个大型后端数据库,它具有我正在使用的以下类结构:

public class InputClass
{
    public int id { get; set; }
    public string text { get; set; }
    public string icon { get; set; }
    public int? parentId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,每个元素都可以有一个父 ID,它最终会生成一个用户可以与之交互的树形信息列表。

使用以下示例数据作为示例:

var inputList = new List<InputClass>();
inputList.Add(new InputClass() { id = 1, text = "Item #1"});
inputList.Add(new InputClass() { id = 2, text = "Item #2" });
inputList.Add(new InputClass() { id = 3, text = "Item #3" });
inputList.Add(new InputClass() { id = 4, text = "SubItem #1", parentId = 1 });
inputList.Add(new InputClass() { id = 5, text = "SubItem #2", parentId = 1 });
inputList.Add(new InputClass() { id = 6, text = "SubItem #3", parentId = 2 });
inputList.Add(new InputClass() { id = 7, text = "Sub-Sub Item #1", parentId = 4 });
Run Code Online (Sandbox Code Playgroud)

我想传递一个 ID # 并检索用该 parentID 标记的所有元素的列表。例如,如果我的 ID 号为 1,则结果应如下所示:

ID  Name
4   Subitem #1
5   Subitem #2
7   Sub-Sub Item #1
Run Code Online (Sandbox Code Playgroud)

如您所见,结果应该返回位于 ID #1 下方的所有内容,包括 ID #7 的项目(即使它的父 ID 为 4,项目 #4 的父项也是 #1)。

我希望以上是有道理的,关于如何在 LINQ 中实现这一点的任何想法?

Har*_*sad 5

Recursive 方法。

public static IEnumerable<InputClass> Recursive(List<InputClass> items, int toplevelid)     
{
    List<InputClass> inner = new List<InputClass>();
    foreach (var t in items.Where(item=>item.parentId ==toplevelid))
    {
        inner.Add(t);
        inner = inner.Union(Recursive(items, t.id)).ToList();
    }       

    return inner;
}
Run Code Online (Sandbox Code Playgroud)

在职的 Demo