So, I’m working with data stored in a CMS system (specifically Sitecore… ensue love/hate). I have the ability to select a particular item in a tree and access its immediate children. Unfortunately, I’m missing the full power of SQL to retreive and mangle.
Now in times gone by, I might write a function taking an item as a parameter that recursively checked the desired criterea on every item encountered. There’s just something… overcomplicated about this, however. One differing approach is separate out a function that pulls in all children of an item recursively:
MyItemLibrary.GetChildrenRecursively(item);
This just feels a little… wrong, conceptually. I mean, really, we’re wanting to perform an action objectively on the item itself. Enter .NET extension methods: despite not having access to the source of the Item class, I can still extend it with a related utility without going so far as creating a subclass:
class MyItemLibrary { public static item[] GetChildrenRecursive(this Item startItem) { /* code… */ }
var myItem = Database.GetItem(“path”);
var allChildren = myItem.GetChildrenRecursive();
…allowing me to call the function on the item – conceptually right!
I then still needed the ability to perform SQL-style querying and sorting on the resulting object list. Enter LINQ (combined with an anonymous type):
var podcasts = from item in Sitecore.Context.Item.Parent.GetChildrenRecursive().ToArray()
where item.Template.Name == “Podcast”
where item.Fields["Tags"].Value.Contains(TagName)
orderby Datetime.Parse(item.Fields["Date"].Value)
select new
{
Name = item.Fields["Subtitle"].Value,
Tags = SitecoreUtility.ParseTags(item.Fields["Tags"].Value, “/AboutUs/Podcasts/tag.aspx”),
Description = item.Fields["Description"].Value,
MediaFile = item.Fields["MediaFile"].Value
};
Now sure, you can argue about reusability – but the sheer small size of code required here moots that in practicality; the other truth being that reusability is not locked out – for example, I can if desired at a later date, easily convert that anonymous class to a regular class.
Programmer convenience is often understated. Ideologies aside, I’ve found .NET/C# to be a great tool for getting things done.
Leave a Reply