Selecting your youngest child

In this thread on the SDN5 Forum someone is asking for a way to select the youngest child of an item. I’ve written a quite simple code snap for this:

 

public static Item GetYoungestChildUsingApi(Item parent)
{
if (parent == null)
{
throw new ArgumentException(“The object ‘parent’ cannot be null”);
}

//Check for children
if(parent.HasChildren)
{
//I know the parent has at least one child, select it
Item youngestChild = parent.Children[0];

//Walk trough children starting with child 2
//When tyheir publishing date is lower then the current selected youngest child, set as youngest child
for (int i = 1; i < parent.Children.Count; i++)
{
if (parent.Children[i].Publishing.PublishDate < youngestChild.Publishing.PublishDate)
{
youngestChild = parent.Children[i];
}
}

return youngestChild;
}
else
{
return null;
}
}

 

 But now I’m wondering, is there a way to do the same using XPath :D? Does anyone know? Help me, please!

 

public static Item GetYoungestChildUsingXPath(Item parent)
{
if (parent == null)
{
throw new ArgumentException(“The object ‘parent’ cannot be null”);
}

//Check for children
if (parent.HasChildren)
{
Item youngestChild;

youngestChild = parent.Axes.SelectSingleItem(“query“);

return youngestChild;
}
else
{
return null;
}
}

One thought on “Selecting your youngest child”

  1. Well, you’re right. It CAN be done in a number of ways.

    But using an xpath to do comparisons may be a bit cumbersome, and I would not recommend it. Also, I am not sure it’s fast enough, as I believe it’s slower than your code above. It is, however, a good exercise. I leave it to you to find the solution. 🙂

    Also, while considering XPath, also consider Sitecore path? This may be an option too? (again, this is not really faster, as Sitecore would do the same approach as you do above, but I think it’s faster than XPath, and more elegant).

    One last comment. Instead of the children[0], you could do the parent.children which gives you a list of items. Then iterate it.

    Best, Lars

Comments are closed.