【问题标题】:Writing a recursive query and join with another list编写递归查询并加入另一个列表
【发布时间】:2016-06-11 04:15:41
【问题描述】:

我正在尝试显示数据库中的文章,但我为类别创建了递归表。所以问题是当父类别选择时,我无法从儿童类别中检索文章。

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();

再次没有成功...

如果有人有解决方案请告诉我。

【问题讨论】:

    标签: c# entity-framework linq recursion


    【解决方案1】:

    您可以使用以下内容

    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

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

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2012-10-21
      • 2014-06-22
      • 1970-01-01
      • 2013-09-20
      相关资源
      最近更新 更多