Sitecore Basics - item.Children

Lets get down to the basics!

To get child items in Sitecore, there are 2 ways to retrieve them:

  • item.Children
  • item.GetChildren()

Both will retrieve ALL children of an item. The difference is that with GetChildren you have the ability to modify the result a little bit since you have the following ChildListOptions to choose from:

ChildListOptions.None
ChildListOptions.IgnoreSecurity
ChildListOptions.AllowReuse
ChildListOptions.SkipSorting

The problem

The biggest caveat is that these methods will retrieve child items even if they don't have a version for the current context language in Sitecore.

This can be ok for the code you are writing. But can result in unexpected behaviour ! One of the examples is when building a Sitemap.

Another example - which was the inspiration for this blog post - was an implementation of a custom contents resolver for a JSON rendering.

We don't want to return Sitecore items that don't have a version in the language that the request is in. The current behaviour was that we were rendering items with info from Shared fields and with all other fields empty.

The fix

Check what the versions count is! That's it, pretty straightforward and an easy way to make sure that you have an Item that actually has a version in Sitecore as well.

Some examples:

item.Versions.Count

item.Children.Where(m => m.Versions.Count > 0)