Kamran
Kamran

Reputation: 4100

Sitecore Delete the most newly added child

In sitecore I want to delete the newly added child.

item.DeleteChildren(); 

Delete all the children under item But I want to delete the most updated child or the newly added child.

Upvotes: 0

Views: 69

Answers (2)

Amir Setoudeh
Amir Setoudeh

Reputation: 500

You can also use Linq:

var newestItem = item.Children.OrderByDescending(child => child.Statistics.Created).FirstOrDefault();

If (newestItem != null)
    newestItem.Delete();

Upvotes: 2

Martin Davies
Martin Davies

Reputation: 4456

I would just loop through the items and see which one was created most recently. Something like this:

Item newestItem = null;
foreach(Item child in parent.Children)
{
    if (newestItem == null || child.Statistics.Created > newestItem.Statistics.Created)
    {
        newestItem = child;
    }
}

if (newestItem != null)
{
    newestItem.Delete();
}

I've used Item.Statistics.Created here, but Item.Statistics.Updated is also available

Upvotes: 4

Related Questions