2016-02-28 46 views
1

我想從數據庫中顯示文章,但我創建了遞歸表的類別。所以問題是當選擇父類別時,我無法從子類別中檢索文章。寫一個遞歸查詢並加入另一個列表

public class Categories 
{ 
    public int id { get; set; } 

    public string Category { get; set; } 

    public int? parentId { get; set; } 

    public IList<Categories> ChildMenu { get; set; } 
} 

和Article類爲

public class Article 
{ 

    public int id { get; set; } 

    public string Name{ get; set; } 

    public int CategoryId{ get; set; } 

    .... etc 

} 

我創造了這個方法來創建類的遞歸的列表,並與文章加入,但它沒有工作

private IEnumerable<Categories> GetCatList(int category) 
{ 
    return db.Categories.Where(x => x.parentId == category || x.id == category).Union(db.Categories.Where(x => x.parentId == category).SelectMany(y =>GetCatList(y.id))); 
} 

我用AsHierarchy

var a = db.Categories.ToList().AsHierarchy(e => e.id, e => e.parentId,category); 

catModel = (from prod in ArticleList() 
      join cats in a.ToList() 
       on prod.Category equals cats.Parent.Category 
       select prod).ToList(); 

a獲得成功...

請如果有人有解決方案讓我知道。

回答

0

您可以使用以下

public static void FindTree(int? parent,List<Category> list,ref List<Category> result) 
    { 
     if(list!=null && list.Count >0) 
     { 
      var details = list.Where(x=>x.ParentId == parent).ToList(); 
      foreach(var detail in details) 
      { 
       result.Add(detail); 
       FindTree(detail.Id,list,ref result); 
      } 
     } 

    } 

這裏工作demo

注:此方法將檢索所有的子樹和排除的父節點,您可以包括它,如果你想要的。

希望能幫到你

相關問題