Surendra Sharma

Surendra Sharma

Search This Blog

Thursday, September 10, 2015

One line of C# code to check item's base templates in Sitecore



As we know Sitecore allow both multiple and multi-level inheritance. If we template is inherited from multiple and multi-level inheritance then it’s very cumbersome to check the base template by using code. However here is simple scenario with only line of code to achieve it.

For example, suppose you have below content tree with parent node is Fruit

·         Fruits
o    Apple 1 : base template Apple
o    banana 1 : base template Banana
o    Apple 2 : base template Apple
o    Mango 1 : base template Mango
o    Mango 2 : base template Mango
o    Green Apple 1: base template Apple, Green Apple

Now if anyone want only items which are of Apple types then we can achieve it in single line of code as 

rptFruit.DataSource = ((Item)Fruits).Children.Where(x => x.Template.BaseTemplates.Any(y => y.ID.Equals(AppleTemplateId)));

If you are trying to access children of any item and want to access only those children items which are inherited from one particular type of template then use LINQ as <item>.Template.BaseTemplates.Any() method.
 
Please leave your comments or share this code if it’s useful for you.

No comments:

Post a Comment