My Sitecore Item has children of different Templates.

To query them, I use the following field declaration:

[SitecoreQuery("*[@@templateid = '{ID of my Template}']", 
InferType = true, IsRelative = true, IsLazy = false)]
    public virtual IEnumerable<MyItemType> MyItemName{ get; set; }

Is there a more efficient way to retrieve them without having to use Sitecore Query?


Why not just have them in one list and just get the ones you want when you check the list?

public class MyItemBaseType {
    public virtual string BaseProperty { get; set; }

public class MyItemType1 {
    public virtual string MyItemType1Property { get; set; }

public class MyItemType2 {
    public virtual string MyItemType2Property { get; set; }
[SitecoreChildren(InferType = true)]
public virtual IEnumerable<MyItemBaseType> MyItems { get; set; }

Then you could access them like so:

var theItem = getitem();

IEnumerable<MyItemType1> type1s = theItem.OfType<MyItemType1>();
string basePropertyValue = type1s.First().BaseProperty;
string type1PropertyValue = type1s.First().MyItemType1Property;

IEnumerable<MyItemType2> type2s = theItem.OfType<MyItemType2>();
basePropertyValue = type2s.First().BaseProperty;
string type2PropertyValue = type2s.First().MyItemType2Property;
  • So, the reason this works is that .OfType<T> is cheaper than the Sitecore Query? – Emanuele Ciriachi May 20 '19 at 8:33
  • Sort of. The difference is that when I call OfType<T>() above, all the items have already been loaded into memory, so it's doing a simple .NET type check. If you create multiple lists with different types in them, you are executing multiple queries to the database (one for each type) to get the contents of those lists. – Dan Sinclair Aug 28 '19 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.