Filtering whole of hierarchical list with LINQ
I have a simple hiearchical list of objects "ProductGroups" (IQueryable). Each "ProductGroup" has a collection of ProductGroups called "Children",an integer ParentId field and a boolean "IsEnabled" field.
public class ProductGroup
{
public int Id;
public int ParentId;
public ICollection<ProductGroup> Children;
public bool IsEnabled;
}
I want to be able to return a tree of ProductGroups where "IsEnabled" is true.
At the moment, if I do
ProductGroups.Where(x => x.IsEnabled)
This returns the enabled products. If I do
ProductGroups.Where(x => x.ParentId == null)
This returns the roots. I want to be able to return a full tree excluding the disabled items in the neatest way possible (i.e. not using for loops after querying the collection).
ProductGroup1 (IsEnabled == true)
|
--------- ProductGroup2 (IsEnabled == true)
| |
| ----------- ProductGroup4 (IsEnabled == false)
|
--------- ProductGroup4 (IsEnabled == false)
i.e. Return开发者_如何学Python ProductGroup1 with 1 child ProductGroup2
Thanks
I'm not sure of your exact needs with the filtered collection. I'm looking at it as a View-Model
. And a recursive extension method provides you with a neat way to achieve this filter:
public static class Helper
{
public static ICollection<ProductGroup> EnabledWithChildren(this ICollection<ProductGroup> source)
{
var result = new List<ProductGroup>();
foreach (var ele in source)
{
if(ele.IsEnabled == true)
{
var productGroup = new ProductGroup{Id = ele.Id, IsEnabled = ele.IsEnabled, ParentId = ele.ParentId};
if(ele.Children != null && ele.Children.Count() > 0)
productGroup.Children = ele.Children.EnabledWithChildren();
result.Add(productGroup);
}
}
return result;
}
}
And usage:
public class ProductGroup
{
public int Id;
public int? ParentId;
public ICollection<ProductGroup> Children;
public bool IsEnabled;
static void Main()
{
var filteredProductGroups = ProductsGroups.EnabledWithChildren();
}
}
精彩评论