2016-05-21 101 views
0

我試圖讓所有兒童MenuItems與子分區直到結束,但此代碼只獲得第一級。遞歸獲取所有子類

如何將此代碼轉換爲管理該功能?

public class MenuItem : IEntityBase 
{ 
    public int Id { get; set; } 
    public string Text { get; set; } 
    public virtual ICollection<MenuItem> Children { get; set; } 
    public virtual MenuItem Parent { get; set; } 
    public bool onMenu { get; set; } 

    public MenuItem() 
    { 
     Children = new List<MenuItem>(); 
    } 
} 

IEnumerable<Entity.MenuItem> _menuItemList = _menuItemRepository.FindByIncluding(x => x.Parent == null && x.onMenu == true, t => t.Children); 

public virtual IEnumerable<T> FindByIncluding(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties) 
{ 
    IQueryable<T> query = _context.Set<T>(); 
    foreach (var includeProperty in includeProperties) 
    { 
     query = query.Include(includeProperty); 
     query = query.Where(predicate); 
    } 
    return query.AsEnumerable(); 
} 

回答

1

你必須使用遞歸。

public List<MenuItem> GetItems (MenuItem item) { 
    var items = item.Children; 

    for (var i=0; i<item.Children.Count; i++) { 
     var child = item.Children[i]; 
     items.AddRange(GetItems(child)); 
    } 

    return items; 
} 

var allItems = GetItems(yourMainItem); 

這會得到所有的孩子,孩子的孩子等,直到你找回他們全部。

1

你的代碼應該工作。您應該從FindByIncluding方法獲得第一級別,但也應該加載Children屬性。

如果你想返回所有的MenuItems在一個集合你應該使用這樣的事情:

public class MenuItem : IEntityBase 
{ 
    //Rest of your code goes here 

    public IEnumerable<MenuItem> GetDescendants(bool includeItself = true) 
    { 
     if (includeItself) 
     { 
      yield return this; 
     } 

     foreach (MenuItem menuItem in this.Children) 
     { 
      foreach (MenuItem descendant in menuItem.GetDescendants(includeItself: true)) 
      { 
       yield return descendant; 
      } 
     } 
    } 
} 

現在,你可以通過調用得到一個集合所有的MenuItems:

IEnumerable<Entity.MenuItem> _menuItemList = _menuItemRepository.FindByIncluding(x => x.Parent == null && x.onMenu == true, t => t.Children); 
IEnumerable<Entity.MenuItem> _allItems = GetAllMenuItems(_menuItemList); 

public IEnumerable<MenuItem> GetAllMenuItems(IEnumerable<MenuItem> rootMenuItems) 
{ 
    IEnumerable<MenuItem> result = rootMenuItems; 

    foreach (MenuItem menuItem in rootMenuItems) 
    { 
     result = result.Concat(menuItem.GetDescendants(false)) 
    } 

    return result; 
}