zoukankan      html  css  js  c++  java
  • 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;
    }

    执行结果如下:

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

  • 相关阅读:
    ole辅助类sqlhelperaccess
    Asp.net中常用的26个性能优化方法
    MVP模式的相关知识
    ASP.NET AJAX入门系列
    非常实用]Asp.net常用的51个代码
    一步一步学Silverlight 系列文章
    .NET设计模式系列文章
    Asp.net添加上传进度条
    asp.net 用ajax实现文件上传
    增加弹出层的拖拽功能
  • 原文地址:https://www.cnblogs.com/jhuang-com/p/7429972.html
Copyright © 2011-2022 走看看