EPiServer  /  CMS September 02, 2009

Convert a LinkItemCollection to a list of PageData

When using the Link collection property in EPiServer CMS I often find my self needing to convert it’s values, that is a collection of LinkItems, into a list of PageData objects. Of course we can’t trust that all of the items are really links to local pages on the site, unless we use some custom property, so I must first check that each item can be mapped to a local page before trying to add it to the list. Luckily, some time ago I wrote a simple utility function for doing just that. Or, more likely, I picked it up on the EPiServer World forum and customized it a bit :)

Anyhow, I’ve been meaning to post this little utility function for quite some time now, and now I’ve finally gotten around to it.

The method is an extension method for the LinkItemCollection class and returns an ordered list of all items in the collection that can be mapped to local pages “converted” to PageData objects. I’ve removed the namespace for brevity.

using System.Collections.Generic;
using EPiServer;
using EPiServer.Core;
using EPiServer.SpecializedProperties;
using EPiServer.Web;

public static class LinkItemCollectionUtility
{
    public static List<PageData> ToPages(this LinkItemCollection linkItemCollection)
    {
        List<PageData> pages = new List<PageData>();

        foreach (LinkItem linkItem in linkItemCollection)
        {
            string linkUrl;
            if (!PermanentLinkMapStore.TryToMapped(linkItem.Href, out linkUrl))
                continue;

            if (string.IsNullOrEmpty(linkUrl))
                continue;

            PageReference pageReference = PageReference.ParseUrl(linkUrl);

            if (PageReference.IsNullOrEmpty(pageReference))
                continue;

            pages.Add(DataFactory.Instance.GetPage((pageReference)));
        }

        return pages;
    }
}

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Joel Abrahamsson

Joel Abrahamsson

I'm a passionate web developer and systems architect living in Stockholm, Sweden. I work as CTO for a large media site and enjoy developing with all technologies, especially .NET, Node.js, and ElasticSearch. Read more

Comments

comments powered by Disqus

My book

Want a structured way to learn EPiServer 7 development? Check out my book on Leanpub!

More about EPiServer CMS