How to get the first TreeNode from the TreeNodeCollection using API and FirstOrDefault() method

This article provides an example of getting the first TreeNode from the TreeNodeCollection of CMSContext.CurrentDocument.Children using LINQ method FirstOrDefault().
There is a small issue with casting objects for LINQ method FirstOrDefault(), because it’s working with the data type of IEnumerable. Casting the TreeNodeCollection to IEnumerable data type can be a little bit difficult.  At first sight, it seems that the following code should work:
TreeNodeCollection myChildren = CMSContext.CurrentDocument.Children; TreeNode firstChild = myChildren.FirstOrDefault();

…but it doesn’t (It looks like the TreeNodeCollection does not properly implement generic collections, so the standard LINQ commands will not work properly).
The correct way is:
using System.Linq; using System.Collections.Generic; // don't forget to use namespaces CMS.TreeEngine.TreeNodeCollection myChildren = CMSContext.CurrentDocument.Children; IEnumerable<CMS.TreeEngine.TreeNode> EnumChild = myChildren.AsEnumerable<TreeNode>(); CMS.TreeEngine.TreeNode myNode = EnumChild.FirstOrDefault<TreeNode>();
Finally you have the first (or the default) TreeNode object from the TreeNodeCollection returned by CMSContext.CurrentDocument.Children.

See also: Managing documentsEnumerable.FirstOrDefault<TSource> Method (IEnumerable<TSource>)

Applies to: Kentico CMS version 5.0 through version 7.0
Share this article on   LinkedIn

Martin Danko

Let me guide you on your journey of success. I will show you how to optimize your content production with Kentico Draft. Check out