使用递归方法测试数据以构建树状菜单?

时间:2011-10-18 12:50:27

标签: c# recursion

我似乎无法理解这一点。我需要构建一些测试数据来构建一个树状菜单,但是我得到一个stackverflow错误,因为它只是继续进行或者我只获得第一级别的子进程。这是我目前的代码:

private MenuItem _menuItem;
private int _start = 1;
private const int Stop = 5;

public void BuildMenu()
{
    var numberOfChildren = new Random((int) DateTime.Now.Ticks).Next(3, 40);
    AutoMapper.Mapper.CreateMap<MenuItem, MenuItemDto>().ConvertUsing<MenuItemConverter>();
    _menuItem = new MenuItem() {Id = Guid.NewGuid(), Name = "Main Menu"};
    _menuItem.ChildMenuItems = BuildChildItems(_menuItem, numberOfChildren);

    var menuDto = AutoMapper.Mapper.Map<MenuItem, MenuItemDto>(_menuItem);
}

public ICollection<MenuItem> BuildChildItems(MenuItem parentMenuItem, int numberOfChildren)
{
    var childItems = new Collection<MenuItem>();

    _start += 1;

    for (var i = 0; i <= numberOfChildren; i++)
    {
        var childItem = new MenuItem()
                            {
                                Id = Guid.NewGuid(),
                                ParentItemId = parentMenuItem.Id,
                                Parentitem = parentMenuItem,
                                Name = "Child Menu Item  " + DateTime.Now
                            };

        if (_start != Stop)
        {
            childItem.ChildMenuItems = BuildChildItems(childItem, numberOfChildren);
        }

        childItems.Add(childItem);
    }

    return childItems;
}

public class MenuItem
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid? ParentItemId { get; set; }
    public MenuItem Parentitem { get; set; }
    public ICollection<MenuItem> ChildMenuItems { get; set; }
}

虽然这有效,但您会注意到_start和Stop变量。我把它们放进去,所以我没有;得到一个stackoverflow,但显然这就是为什么我只得到每个人口居住的第一级。我想我需要跟踪我所处的水平,但不确定如何跟踪它。不知道为什么我今天画空白....

1 个答案:

答案 0 :(得分:2)

这给出了想法,而不是实际查看您的特定对象模型!有一个int代表你想要去的级别数。将其发送到方法中,在每次递归时递减它,直到它为零。

public void BuildChildItems(MenuItem parentMenuItem, int numberOfChildren, int level)
{
  if(level == 0) return;

  var results_for_this_level = create_results_for_this_level();
  parentMenuItem.Add(results_for_this_level);


  foreach(sibling in results_for_this_level)
  {
     BuildChildItems(sibling, numberofChildren, level-1) //note the decrement of level here
  } 
    }