zoukankan      html  css  js  c++  java
  • c#通用递归生成无限层级树

    NewsType结构:

    Id

    ParentId

    Name

    children(List<NewsType>)

    public void LoopToAppendChildren(List<NewsType> all,  NewsType curItem)
    {
        var subItems = all.Where(ee => ee.ParentId==curItem.Id).ToList(); 
        curItem.children = new List<NewsType>();
        curItem.children.AddRange(subItems);
        foreach (var subItem in subItems)
        {
            LoopToAppendChildren(all, subItem);//新闻1.1
        }
    }

    //通用 ParentId,Id,children 用了反射效率不高

    public void LoopToAppendChildren<T>(List<T> all, T curItem, string parentIdName = "ParentId", string idName = "Id", string childrenName = "children")
    {
      var subItems = all.Where(ee => ee.GetType().GetProperty(parentIdName).GetValue(ee, null).ToString() == curItem.GetType().GetProperty(idName).GetValue(curItem, null).ToString()).ToList(); //新闻1

      curItem.GetType().GetField(childrenName).SetValue(curItem, subItems);
      foreach (var subItem in subItems)
      {
        LoopToAppendChildren(all, subItem);//新闻1.1
      }
     }


    调用:
    //实例化一个根节点 NewsType rootRoot = new NewsType(); rootRoot.Id = 0; rootRoot.ParentId = 0; rootRoot.Name="根节点"; LoopToAppendChildren(dc.NewsType.ToList(), rootRoot);

    原文地址:http://www.cnblogs.com/xuejianxiyang/p/5027280.html

  • 相关阅读:
    计算机学院大学生程序设计竞赛(2015’12)Study Words
    离散化
    一键拨打
    python中Strip()函数的用法
    笨方法学python 22,前期知识点总结
    笨方法学python之读写文件、open函数的用法
    Linux 多线程串口通信
    RSA加密前言
    GrabCut--Opencv篇
    队列
  • 原文地址:https://www.cnblogs.com/xuejianxiyang/p/5027280.html
Copyright © 2011-2022 走看看