创建一个递归函数以响应不同的对象[关闭]

问题描述 投票:0回答:1

我从 HTTP 请求接收以下数据以获取所有可用菜单:

[
  {
    "ID": "2",
    "Name": "Home",
    "ParentID": "1",
    "Path": "/home"
  },
  {
    "ID": "3",
    "Name": "Contacts",
    "ParentID": "1",
    "Path": "/contacts"
  },
  {
    "ID": "4",
    "Name": "Help",
    "ParentID": "3",
    "Path": "/contacts/help"
  },
  {
    "ID": "5",
    "Name": "Form",
    "ParentID": "4",
    "Path": "/contacts/help/form"
  },
  {
    "ID": "6",
    "Name": "Information",
    "ParentID": "4",
    "Path": "/contacts/help/information"
  }
]

有了这些信息,我需要创建一个 HTTP POST 方法,我需要使用以下结构来响应

[
  {
    "Name": "Home",
    "Path": "/home",
    "Childrens": []
  },
  {
    "Name": "Contacts",
    "Path": "/contacts",
    "Childrens": [
      {
        "Name": "Help",
        "Path": "/contacts/help",
        "Childrens": [
          {
            "Name": "Form",
            "Path": "/contacts/help/form",
            "Childrens": []
          },
          {
            "Name": "Information",
            "Path": "/contacts/help/information",
            "Childrens": []
          }
        ]
      }
    ]
  }
]

我的方法:

[AllowCrossSiteJson]
[ActionName("GetMenu")]
[AcceptVerbs("POST", "OPTIONS")]
[Route("menu")]
public ActionResult GetMenuRest()
{
  var allMenus = GetMenu(); // Get menus from external API

  List<Item> response = new List<Items>{
    // TODO
  };

  return new HttpStatusContentResult(response);
}

public List<Item> GetMenu()
{
  using (var client = new HttpClient())
  {
      var endpoint = new Uri("https://.../gettree"); // External API to get tree
      var response = client.GetAsync(endpoint).Result;
      var menus = JsonConvert.DeserializeObject<List<Item>>(response.Content.ReadAsStringAsync().Result);
      return menus; // Menus available
  }
}

备注:

ID财产始终是唯一的;

ParentID属性是对父级的引用(ID)(ParentID=1是源“/”)。每个对象都有一个ParentID

我该怎么做?我可以使用递归函数来创建我需要的response吗?

附注如果您只给我建议和提示,我将不胜感激。

(已编辑)

c# arrays algorithm recursion return
1个回答
-2
投票

我在 python 中用两步完成了这个(抱歉不知道 csharp 语法):

  • 创建哪些节点是哪些其他节点的子节点的映射
  • 使用更新的格式构建一个新节点并递归构建其子节点

这是示例代码:

def recAdd(vck, objs, target):
    children = []
    for x in vck[target]:
        children.append(recAdd(vck, objs, x))
    obj = {
            "Name" : objs[target]["Name"],
            "Path" : objs[target]["Path"],
            "Children" : children
            }
    return obj

def convert(objs):
    ids = {}
    for obj in objs:
        ids[obj["ID"]] = obj

    valueIsChildOfKey= {}
    for k,v in ids.items():
        if k not in valueIsChildOfKey.keys():
            valueIsChildOfKey[k] = []
        if v["ParentID"] in valueIsChildOfKey.keys():
            valueIsChildOfKey[v["ParentID"]].append(k)
        else:
            valueIsChildOfKey[v["ParentID"]] = [k]
    out = []
    for x in valueIsChildOfKey["1"]:
        out.append(recAdd(valueIsChildOfKey, ids, x))

    return out
if __name__ == "__main__":
    Results = [ {"ID": "2","Name": "Home","ParentID": "1","Path": "/home"}, { "ID": "3", "Name": "Contacts", "ParentID": "1", "Path": "/contacts" }, { "ID": "4", "Name": "Help", "ParentID": "3", "Path": "/contacts/help" }, { "ID": "5", "Name": "Form", "ParentID": "4", "Path": "/contacts/help/form" }, { "ID": "6", "Name": "Information", "ParentID": "4", "Path": "/contacts/help/information" } ]
    print(convert(Results))
© www.soinside.com 2019 - 2024. All rights reserved.