Subscribe

Close

Thank you for visiting!

Please consider subscribing to the RSS feed or following me on Twitter.

How to sort EPiServer categories

Every once in a while you might want to sort your EPiServer categories. First thing that comes to mind is that the order in which the categories appear in admin mode, is the order by which the categories are sorted when displaying them. Actually, it's not always that way!

EPiServer categories seems to have no built-in sorting when retrieving them as a list when using CategoryList.

Luckily, each and one of the specific categories do have a SortOrder property which is really useful.

You can use that SortOrder property and the generic SortedList class to sort the categories, like this:

SortedList<int, ListItem> sortedCategories = new SortedList<int, ListItem>();
CategoryList cats = CurrentPage.Category;

foreach (int c in cats)
{
Category cat = Category.Find(c);
string catName = Category.Find(cats.GetCategoryName(c)).Name;

ListItem li = new ListItem(catName, catName);
sortedCategories.Add(cat.SortOrder, li);
}

ddCategories.Items.AddRange(sortedCategories.Values.ToArray());

Comments

I know this is really old but you can also use this :

var categories = new List<Category>();
[...]
categories.Sort(new CategoryComparer());


public class CategoryComparer : IComparer<Category>
{
public int Compare(Category x, Category y)
{
if (x.SortOrder == y.SortOrder)
return 0;
else if (x.SortOrder > y.SortOrder)
return 1;
else
return -1;
}
}

To the top