2016-02-28 75 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

注:此方法将检索所有的子树和排除的父节点,您可以包括它,如果你想要的。

希望能帮到你

相关问题