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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM