Extending EPiServer Categories
The other day I asked a question on twitter
Is there an easy way of getting all the selected categories from a sub-category in EPiServer for a page?
If you use CurrentPage.Categories or (CategoryList)CurrentPage["MyCategoryProperty"], you’ll get all the selected categories in one list. What I needed was to only get those that where children of a certain one.
Having gotten no answer and not finding anything in the SDK, I decided to create this functionality as a couple of extension methods.
using System.Linq; using EPiServer.Core; using EPiServer.DataAbstraction; namespace EPiCode.Extensions { public static class CategoryExtensions { public static CategoryCollection GetActiveSubCategories(this CategoryList allActiveCategoryIds, string parentCategoryName) { return allActiveCategoryIds.GetActiveSubCategories(Category.Find(parentCategoryName)); } public static CategoryCollection GetActiveSubCategories(this CategoryList allActiveCategoryIds, int parentCategoryId) { return allActiveCategoryIds.GetActiveSubCategories(Category.Find(parentCategoryId)); } public static CategoryCollection GetActiveSubCategories(this CategoryList allActiveCategoryIds, Category parentCategory) { if (allActiveCategoryIds == null || allActiveCategoryIds.Count < 1 || parentCategory == null) { return null; } CategoryCollection subCategories = Category.Find(parentCategory.ID).Categories; var activeCategories = new CategoryCollection(); for (int i = 0; i < allActiveCategoryIds.Count; i++) { Category category = Category.Find(allActiveCategoryIds.ElementAt(i)); foreach (Category subCategory in subCategories) { if (subCategory.ID == category.ID) { activeCategories.Add(category); } } } return activeCategories; } } }
CategoryCollection activeSubCategories = CurrentPage.Category.GetActiveSubCategories("news");
Note that this will not find the grand or grand grand children, only the direct children of a category.
So what do you think, is this useful? Should I had it to the EPiCode.Extensions project?