Get Item's Children Sorted
By default, the Item's children are sorted first by SortOrder and then by Name.
The ChildList class has a Sort (IComparer) method that allows you to reference your own class, which implements the IComparer interface, and specify your own compare rule inside the Compare method.
You can get the Item’s children in one of the two ways given below:
-
Create a ChildList and pass the Parent Item to the ChildList constructor. For example:
Item homeItem =
Sitecore.Configuration.Factory.GetDatabase("master").Items["/sitecore/content/home"];
ChildList children = new ChildList(homeItem);
-
Reference the Item.Children attribute. For example:
ChildList children = homeItem.Children;
1. Sample code
Here is a sample implementation for the custom compare method:
public class ItemComparer : IComparer
{
public ItemComparer()
{
}
public int Compare(object x, object y)
{
Item item1 = x as Item;
Item item2 = y as Item;
return String.Compare(item1.Name, item2.Name);
}
}
public class Document : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
Item homeItem = Sitecore.Configuration.Factory.GetDatabase("master").Items["/sitecore/content/home"];
ChildList children = new ChildList(homeItem);
ItemComparer comparer = new ItemComparer();
Response.Write("Before sorting: <br/>");
foreach (Item child in children)
{
Response.Write(child.Name+"<br/>");
}
Response.Write("<hr>");
children.Sort(comparer);
Response.Write("After sorting: <br/>");
foreach (Item child in children)
{
Response.Write(child.Name+"<br/>");
}
Response.Write("<hr>");
}