Recursive call return a List, return type causing me issues

前端 未结 5 713
遥遥无期
遥遥无期 2021-02-04 06:12

I have a recursive method that is return me categories, and checking for its sub categories.

So it looks like:

public List GetAllChildCat         


        
相关标签:
5条回答
  • 2021-02-04 06:26
       foreach(Category cat in c.ChildCategories)
          {
                  list.AddRange( GetAllChildCats(cat.CategoryID) )
    
          }
    

    and don't forget the

    return list;
    
    0 讨论(0)
  • 2021-02-04 06:29

    I had the same problem before. Here is the way I solved it:

    public void GetAllChildCategories(ProductCategory ParentCategory)
    {
        ParentCategory.ChildCategories = GetChildCategories(ParentCategory.ID);
    
        foreach(ProductCategory cat in ParentCategory.ChildCategories)
        {
            GetAllChildCategories(cat);
        }
    }
    
    0 讨论(0)
  • 2021-02-04 06:40

    I think this linq version will allow you to avoid the overhead of creating a list:

    public IEnumerable<Category> GetAllChildCats(int categoryid)
    {
        Category c = Get(categoryid);
        return new[] { c }.Concat(c.ChildCategories.SelectMany(cat => GetAllChildCats(cat)));
    }
    

    You can always call ToList() on the returned IEnumerable if you need it.

    0 讨论(0)
  • 2021-02-04 06:43

    Here's a modified version of Jon Skeet's answer using a local method (C# 7) :

        public List<Category> GetAllChildCats(int rootId)
        {
            List<Category> list = new List<Category>();
            Traverse(rootId);
            return list;
    
            void Traverse(int categoryId)
            {
                Category c = Get(categoryId);
                list.Add(c);
    
                foreach (Category cat in c.ChildCategories)
                {
                    Traverse(cat.CategoryID);
                }
            }
        }
    
    0 讨论(0)
  • 2021-02-04 06:45

    Currently you haven't shown anything which actually adds a single category to the list... I'm assuming that as you recurse, you want to add the results of Get(categoryId) as well·

    Preet's solution will certainly work, but here's an alternative which avoids creating all the extra lists:

    public List<Category> GetAllChildCats(int categoryId)
    {
        List<Category> ret = new List<Category>();
        GetAllChildCats(categoryId, ret);
        return ret;
    }
    
    private void GetAllChildCats(int categoryId, List<Category> list)
    {
        Category c = Get(categoryid);
        list.Add(c);
    
        foreach(Category cat in c.ChildCategories)
        {
            GetAllChildCats(cat.CategoryID, list);
        }
    }
    

    This creates a single list, and adds items to it as it goes.

    One point though - if you've already got the child Category objects, do you really need to call Get again? Does each child only contain its ID until you fetch the whole category?

    0 讨论(0)
提交回复
热议问题