我正在尝试从数据库中显示文章,但我为类别创建了递归表。所以问题是当选择父类别时我无法从子类别中检索文章。
=
和文章类
public class Categories
{
public int id { get; set; }
public string Category { get; set; }
public int? parentId { get; set; }
public IList<Categories> ChildMenu { get; set; }
}
我创建了这个方法来创建一个类别递归的列表并加入文章,但它没有工作
public class Article
{
public int id { get; set; }
public string Name{ get; set; }
public int CategoryId{ get; set; }
.... etc
}
我使用了AsHierarchy
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)));
}
再次没有成功......
如果有人有解决方案,请告诉我。
答案 0 :(得分: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
注意:此方法将检索所有子树和排除的父节点,如果需要,可以包含它。
希望它会帮助你