Kamran
Kamran

Reputation: 4100

Get the all the children from a Sitecore item in a parent-child relation

The following code should return all the children and sub-children in a list, but it's not keeping the ordering of parent-child relation. It returns all the parent items first, and then all the child items.

Is it possible somehow to keep the items in order, and get them in a list in the same order as they are in Sitecore?

MainItem contains the items in the parent-child relation:

Item mainItem= Sitecore.Context.Database.GetItem(Settings.GetSetting("MainItem"));
mainItem.Axes.GetDescendants().ToList();

Upvotes: 1

Views: 10999

Answers (1)

Martin Davies
Martin Davies

Reputation: 4456

You could add items to a list recursively:

public void AppendItems(List<Item> itemList, Item item)
{
    foreach(Item childItem in item.Children)
    {
        itemList.Add(childItem);
        AppendItems(itemList, childItem);
    }
}

Usage:

var list = new List<Item>();
list.Add(rootItem);
AppendItems(list, rootItem);

Upvotes: 6

Related Questions