using DS.Module.Core; using DS.Module.Core.Extensions; using DS.WMS.Core.System.Entity; using Microsoft.Extensions.DependencyInjection; using SqlSugar; using Xunit; namespace Ds.WMS.Test; public class TreeTest { private readonly IServiceProvider _serviceProvider; private readonly ISqlSugarClient db; public TreeTest(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; db = _serviceProvider.GetRequiredService(); } [Fact] public void TreeTest1() { TreeNode treeNode1 = new TreeNode("1", "山东", "0"); TreeNode treeNode2 = new TreeNode("2", "北京", "0"); TreeNode treeNode3 = new TreeNode("3", "历下区", treeNode1); TreeNode treeNode4 = new TreeNode("4", "高新区", treeNode1); TreeNode treeNode5 = new TreeNode("5", "历城区", treeNode1); TreeNode treeNode6 = new TreeNode("6", "甸柳庄", treeNode3); TreeNode treeNode7 = new TreeNode("7", "济南长途汽车站东站", treeNode6); TreeNode treeNode8 = new TreeNode("8", "朝阳区", treeNode2); TreeNode treeNode9 = new TreeNode("9", "海淀区", treeNode2); TreeNode treeNode10 = new TreeNode("10", "金盏乡", treeNode8); List list = new List(); list.Add(treeNode1); list.Add(treeNode2); list.Add(treeNode3); list.Add(treeNode4); list.Add(treeNode5); list.Add(treeNode6); list.Add(treeNode7); list.Add(treeNode8); list.Add(treeNode9); list.Add(treeNode10); List trees = BulidTree(list); Assert.True(true); } public class TreeNode { /// /// 子id /// public string Id { get; set; } /// /// 父id /// public string ParentId { get; set; } /// /// 名称 /// public string Name { get; set; } /// /// 子节点 /// public List Children { get; set; } /// /// 无参构造函数 /// public TreeNode() { Children = new List(); } /// /// 有参构造函数 /// /// 子id /// 名称 /// 父id public TreeNode(string id, string name, string parentId) { this.Id = id; this.Name = name; this.ParentId = parentId; Children = new List(); } /// /// 有参构造函数 /// /// 子id /// 名称 /// 父节点 public TreeNode(string id, string name, TreeNode parent) { this.Id = id; this.Name = name; this.ParentId = parent.Id; Children = new List(); } } /// /// 双层循环 /// /// /// public static List BulidTree(List treeNodes) { try { List trees = new List(); foreach (var treeNode in treeNodes) { if ("0" == (treeNode.ParentId)) { trees.Add(treeNode); } foreach (var it in treeNodes) { if (it.ParentId == treeNode.Id) { treeNode.Children.Add(it); } } } return trees; } catch (Exception ex) { throw ex; } } }