c# 父子列表添加 ID

c# parent child list add IDs

我有一个父子列表,我得到的是 JSON

public class Item
{
    public Item()
    {
       this.Items = new List<Item>();
    }

    public string Name { get; set; }
    public DateTime Created { get; set; }
    public string Content { get; set; }
    public string UserId { get; set; }
    List<Item> Items { get; set; }
}

现在假设我得到一个 JSON,我将反序列化为

 string json = "json in here"

 List<Item> listItems = JsonConvert.Dezerialize<List<Item>>(json);

我的问题:我如何解析 List<Item> 并向其添加动态 ID,使其成为这样的东西?

public class Item
{
    public Item()
    {
       this.Items = new List<Item>();
    }

    public string Id { get; set; }
    public string ParentId { get; set; }
    public string Name { get; set; }
    public DateTime Created { get; set; }
    public string Content { get; set; }
    public string UserId { get; set; }
    List<Item> Items { get; set; }
}

Id 是项目 ID(例如可以是 Guid),ParentId 是项目父级的 ID。如果 Item 没有父项,则 ParentId 为空。如果 ParentId 为 null,则 Item 为顶级项目。可以有不止一个父项。

can be Guid for example

这使得很多更容易,因为您不必跟踪使用了哪些 ID。现在这是一个简单的递归工作:

void SetIDs(Item item, string parentId)
{
    item.ParentId = parentId;
    item.Id = Guid.NewGuid().ToString();
    foreach (var i in item.Items)
        SetIDs(i, item.Id);
}

然后只需使用顶级项目的初始空 ID 调用它(根据您的要求,顶级项目有一个 null 父 ID):

SetIDs(someItem, null);

(如果您确实必须跟踪 ID,例如使用 int,那么您可能正在查看一个范围更广的变量,这可能很棘手,或者 out 参数或类似性质的东西可能很难看。)