c#:无限极树形结构

最近一直在研究树形结构菜单,无意中让我弄了出来。先上代码:

首先需要这个的一个类

public class Tree
{
public int id { get; set; }
public string address { get; set; }
public int parent_id { get; set; }
public int depth { get; set; }
}

private static List<Tree> listTree = new List<Tree>(); // 定义一个全局的list来存放数据
static void Main(string[] args)
{
//初始化数据
var data = new List<Tree>()
{
new Tree{ id=1, address="安徽", parent_id = 0, depth=1 },
new Tree{id=2, address="江苏", parent_id = 0, depth=1},
new Tree{id=3, address="合肥", parent_id = 1, depth=2},
new Tree{id=4, address="庐阳区", parent_id = 3, depth=3},
new Tree{id=5, address="大杨镇", parent_id = 4, depth=4},
new Tree{id=6, address="南京", parent_id = 2, depth=2},
new Tree{id=7, address="玄武区", parent_id = 6, depth=3},
new Tree{id=8, address="梅园新村街道", parent_id = 7, depth=4},
new Tree{id=9, address="上海", parent_id = 0, depth=1},
new Tree{id=10, address="黄浦区", parent_id = 9, depth=2},
new Tree{id=11, address="外滩", parent_id = 10, depth=3},
new Tree{id=12, address="安庆", parent_id = 1, depth=2}
};

var list = GetSubTree(data, 0);

foreach (var item in list)
{
string space = string.Empty;
if (item.depth != 1)
{
for (var i = 0; i < item.depth; i++)
{
space += " ";
}
}

Console.WriteLine(space + "id={0},address={1},parent_id={2},depth={3}", item.id.ToString(), item.address, item.parent_id, item.depth);
}

}
/// <summary>
/// 组装树形结构数据
/// </summary>
/// <param name="data"></param>
/// <param name="parent_id"></param>
/// <returns></returns>
private static List<Tree> GetSubTree(List<Tree> data, int parent_id)
{
foreach (var item in data)
{
if (item.parent_id == parent_id)
{
listTree.Add(item);
GetSubTree(data, item.id);
}
}
return listTree;
}

 

执行结果如下:

 

简简单单,希望大神指点迷津。

 

转载于:https://www.cnblogs.com/jhuang-com/p/7429972.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值