/// <summary>
/// 多级类定义字段
/// </summary>
public class PostAreasTree
{
public string id { get; set; } = "0";
public string parentId { get; set; } = "0";
public int depth { get; set; } = 0;
public string name { get; set; } = null;
public List<PostAreasTree> child;
}

 

/// <summary>
///城市地区获取列表
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPost]
public async Task<JsonResult> GetAreaListTwo()
{
string Clerk = "SELECT * FROM CoreCmsArea ";
DataTable Clerklist = SqlHelper.Query(Clerk); //获取全部数据
var AreasTree = new List<PostAreasTree>(); //定义PostAreasTree list 数组
for (int i = 0; i < Clerklist.Rows.Count; i++) // List 赋值
{
AreasTree.Add(new PostAreasTree()
{
id = Clerklist.Rows[i]["id"].ToString(),
parentId = Clerklist.Rows[i]["parentId"].ToString(),
name = Clerklist.Rows[i]["name"].ToString(),
depth =int.Parse( Clerklist.Rows[i]["depth"].ToString()),
child = null
}) ;
}
var AreaInfo = AreasTree.Where(p => p.parentId == "0").ToList(); // 查询第一级 父id 为0
AreasTree = _Area.getList(AreaInfo, AreasTree); //调用递归方法
var jm = new WebApiCallBack();//定义返回json字符串
jm.status = true;
jm.msg = "数据获取成功 ";
jm.data = AreasTree;

return Json(jm);
}



//递归方法
public List<PostAreasTree> getList(List<PostAreasTree> objectList, List<PostAreasTree> originList)
{
List<PostAreasTree> newList = new List<PostAreasTree>(); //定义新的数组
foreach (var item in objectList) //循环参数父数组
{
List<PostAreasTree> childList = originList.Where(x => x.parentId == item.id).ToList(); //查找父数组的子集
if (childList.Count > 0)
{
item.child = getList(childList, originList); //行数大于0赋值循环调用
}
newList.Add(item);//数组添加值
}
return newList; //返回
}

返回数据

{
  "methodDescription": null,
  "otherData": null,
  "status": true,
  "msg": "数据获取成功 ",
  "data": [
    {
      "child": [
        {
          "child": [
            {
              "child": null,
              "id": "410182",
              "parentId": "410100",
              "depth": 3,
              "name": "荥阳市"
            }
          ],
          "id": "410100",
          "parentId": "410000",
          "depth": 2,
          "name": "郑州市"
        }
      ],
      "id": "410000",
      "parentId": "0",
      "depth": 1,
      "name": "河南省"
    }
  ],
  "code": 0
}
 

 

posted on 2021-08-02 15:41  lwmwsh  阅读(146)  评论(0编辑  收藏  举报