编写递归查询并与另一个列表联接
本文关键字:列表 另一个 递归查询 | 更新日期: 2023-09-27 18:36:29
我正在尝试显示数据库中的文章,但我为类别创建了递归表。所以问题是当选择父类别时,我无法从子类别中检索文章。
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
}
我创建了此方法来创建类别递归列表并与文章连接,但它不起作用
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();
又没有成功...
请 如果有人有解决方案,请告诉我。
您可以使用
以下内容
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);
}
}
}
这是一个工作演示
注意:此方法将检索所有子树和排除的父节点,如果需要,可以包含它。
希望对您有所帮助