我的递归方法有问题。这种方法的行为并不像我希望的那样。
我要做的是获取我的数据库中所有类别的排序列表,这些列表包含名为ChildList的子列表,我试图创建一个递归添加的方法孩子是合法的父母。
在3个级别下,它的行为完全符合我的要求,它将一个Child添加到CategoryViewModel的子列表中。之后,它往往会制作我不想要的重复孩子。
例如,你有
这是我的代码
namespace GUI.Controllers
{
public class HomeController : Controller
{
private readonly IRepository<Category> _repo;
private static List<CategoryViewModel> _sources;
public HomeController(IRepository<Category> repo)
{
_repo = repo;
}
public HomeController()
: this(new Repository<Category>())
{
}
public ViewResult Index()
{
var items = _repo.GetAll().ToList();
var sortedList = new CategoryViewModel();
_sources = items.Select(c => new CategoryViewModel
{
Id = c.Id,
Name = c.Name,
Parent = c.Parent.HasValue ? c.Parent.Value : (Guid?) null,
Products = c.Product.ToList(),
ChildList = new List<CategoryViewModel>()
}).ToList();
_sources = _sources.OrderBy(o => o.Parent).ToList();
var root = _sources.First();
sortedList.Id = root.Id;
sortedList.Name = root.Name;
sortedList.Parent = null;
sortedList.ChildList = _sources.Where(o => o.Parent != null && o.Parent == root.Id).ToList();
foreach (var l in _sources)
{
if(l.Parent == null)
continue;
l.ChildList = _sources.Where(o => o.Parent != null && o.Parent == l.Id).ToList();
if (l.ChildList.Any())
AddItem(l.ChildList, ref sortedList);
}
return View(sortedList);
}
private static void AddItem(List<CategoryViewModel> children, ref CategoryViewModel sortedList)
{
foreach (var child in children)
{
var childs = _sources.Where(o => o.Parent != null && o.Parent == child.Id).ToList();
foreach (var c in childs)
{
child.ChildList.Add(c);
}
if (child.ChildList.Any())
AddItem(child.ChildList, ref sortedList);
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using ClassLibrary.Entities;
namespace GUI.Models
{
public class CategoryViewModel
{
[Required]
public string Name { get; set; }
[Required]
public string SearchString { get; set; }
public Guid Id { get; set; }
public Guid? Parent { get; set; }
public string ParentName { get; set; }
public List<Product> Products { get; set; }
public List<CategoryViewModel> ChildList { get; set; }
}
}
答案 0 :(得分:1)
好的,我发现问题的解决方案是什么;
我的递归方法是代码溢出,我太深入了解而没有理解如何实际使用递归方法。正如他们所说;有一件事导致另一件事,我最终删除了我的AddItem方法,事实证明我的lambda表达式在正确的列表集合中为我排序了列表;最终的代码看起来更干净,现在变得更小了;
public ViewResult Index()
{
var items = _repo.GetAll().ToList();
var categories = items.Select(c => new CategoryViewModel
{
Id = c.Id,
Name = c.Name,
Parent = c.Parent.HasValue ? c.Parent.Value : (Guid?) null,
Products = c.Product.ToList(),
ChildList = new List<CategoryViewModel>()
}).OrderBy(o => o.Parent).ToList();
var sortedCategories = categories.First();
sortedCategories.ChildList = categories.Where(o => o.Parent != null && o.Parent == sortedCategories.Id).ToList();
foreach (var l in categories.Where(l => l.Parent != null))
{
l.ChildList = categories.Where(o => o.Parent != null && o.Parent == l.Id).ToList();
}
return View(sortedCategories);
}