简体   繁体   English

C#父子列表添加ID

[英]c# parent child list add IDs

I have a parent child list which I get as JSON 我有一个以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; }
}

Now imagine I get a JSON that I will deserialize into 现在想象一下,我得到一个将反序列化为的JSON

 string json = "json in here"

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

My question: how can I parse the List<Item> and add dynamically ID's to it so it will be something like this? 我的问题:如何解析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; }
}

The Id is the item Id (can be Guid for example) and ParentId is the Id of the parent for the item. Id是商品ID(例如可以引导),ParentId是商品的父ID。 If Item has no parent then ParentId is null. 如果Item没有父项,则ParentId为null。 If ParentId is null Item is then top item. 如果ParentId为null,则Item为顶层。 There can be more then one parent items. 可以有一个以上的父项。

can be Guid for example 例如可以被引导

That makes this a lot easier, since you don't have to keep track of which IDs have been used. 这使得这一切变得更容易,因为你不必跟踪哪些已经被使用的ID。 Now it's a simple job for recursion: 现在,这是一个简单的递归工作:

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

Then just call it with an initial empty ID for the top-level item (per your requirement that the top-level has a null parent ID): 然后,使用顶级项目的初始空ID调用它(根据您的要求,顶层具有null父ID):

SetIDs(someItem, null);

(If you did have to track the IDs, such as with an int for example, then you'd likely either be looking at a higher-scoped variable which can be tricky or out parameters or something of that nature which can be ugly.) (如果您确实必须跟踪ID(例如,使用int进行跟踪),那么您可能正在寻找一个范围较广的变量,该变量可能很棘手,或者是out参数的范围,或者是某种性质的,可能很丑陋的变量。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM